2014-09-12 8 views
2

Я полный новичок в программировании на Java, я хочу динамически создавать объекты в Java во время выполнения, я проверил формы и попробовал некоторый код, но ничего действительно не работает.динамически создавать объекты в цикле

вот мой код .. вся помощь очень ценится :)

import java.util.Scanner; 

    public class Main{ 
    public static void main(String[] args){ 
    String carName; 
    String carType; 
    String engineType; 
    int limit; 

    Scanner in = new Scanner(System.in); 
    System.out.print("Enter the number of Cars you want to add - "); 
    limit = in.nextInt(); 

    for(int i = 0; i <limit; i++){ 

    Cars cars[i] = new Cars(); 

    System.out.print("Enter the number of Car Name - "); 
    carName = in.nextLine(); 

    System.out.print("Enter the number of Car Type - "); 
    carType = in.nextLine(); 

    System.out.print("Enter the Engine Type - "); 
    engineType = in.nextLine(); 

    cars[i].setCarName(carName); 
    cars[i].setCarType(carType); 
    cars[i].setEngineeSize(engineType); 
    String a = cars[i].getCarName(); 
    String b = cars[i].getCarType(); 
    String c = cars[i].getEngineeSize(); 
    System.out.println(a,b,c); 

    } 
    } 
    } 

Класс автомобиля выглядит следующим образом ..

public class Cars{ 
    public String carName; 
    public String carType; 
    public String engineeSize; 

    public void Cars(){ 
    System.out.println("The Cars constructor was created ! :-) "); 
    } 

    public void setCarName(String cn){ 
    this.carName = cn; 
    } 

    public void setCarType(String ct){ 
    this.carType = ct; 

    } 

    public void setEngineeSize(String es){ 
    this.engineeSize = es; 

    } 

    public String getCarName(){ 
    return this.carName; 
    } 



    public String getCarType(){ 
    return this.carType; 
    } 

    public String getEngineeSize(){ 
    return this.engineeSize; 
    } 


    } 

ответ

0

Вы находитесь на правильном пути, однако есть несколько ошибок и ненужных бит.

КАРС Класс

Ваш класс Автомобили в основном хорошо, (хотя на мой взгляд Car бы больше смысла), однако ваш конструктор не имеет смысла, вы имели public void Cars(), void означает «этот метод ничего не возвращает», но вы хотите вернуть Cars объект, то есть ваш конструктор должен стать:

public Cars() 
{ 
    System.out.println("The Cars constructor was created ! :-) "); 
} 

Ваш главный класс

Вы были очень близки и здесь, ваш основной вопрос создавал cars массиву limit раз:

for(int i = 0; i < limit; i++) 
{ 
    Cars cars[i] = new Cars(); 
    //Other code 
} 

Массив должен быть вне цикла for.

Настоящий пересмотренный Main класс в полном объеме, комментарии должны объяснять довольно хорошо, что я сделал и почему.

import java.util.Scanner; 

public class Main{ 

public static void main(String[] args){ 
    //The strings here were unnecessary 
    int limit; 

    Scanner in = new Scanner(System.in); 

    System.out.print("Enter the number of Cars you want to add - "); 
    limit = in.nextInt(); 
    in.nextLine(); //nextInt leaves a newLine, this will clear it, it's a little strange, but it makes sense seeing as integers can't have newlines at the end 

    //Make an array of Cars, the length of this array is limit 
    Cars[] cars = new Cars[limit]; 

    //Iterate over array cars 
    for(int i = 0; i < limit; i++) 
    { 
     //Read all the properties into strings 
     System.out.println("Enter the number of Car Name - "); 
     String carName = in.nextLine(); 

     System.out.println("Enter the number of Car Type - "); 
     String carType = in.nextLine(); 

     System.out.println("Enter the Engine Type - "); 
     String engineType = in.nextLine(); 

     //Set the object at current position to be a new Cars 
     cars[i] = new Cars(); 

     //Adjust the properties of the Cars at this position 
     cars[i].setCarName(carName); 
     cars[i].setCarType(carType); 
     cars[i].setEngineeSize(engineType); 

     //We still have the variables from the scanner, so we don;t need to read them from the Cars object 
     System.out.println(carName+carType+engineType); 
    } 
    in.close(); //We don't need the scanner anymore 
    } 
} 

Готовые печатал это и понял, что речь идет о двух лет :)

Смежные вопросы