2014-03-06 5 views
0
public static int askingAmount() { 
    System.out.println("How many persons are there in your company?"); 
    Scanner amountS = new Scanner(System.in); 
    amount = amountS.nextInt(); 
    System.out.println(amount); 
    amountS.close(); 
    return amount; 
} 
public static void makingPersons() { 
    for (int i=0 ; i<amount ; i++) { 
     int personNumber=0; 
     Person person[i] = new Person(); //<--- The problem 
     System.out.println("person"); 
    } 
} 

첫 번째 방법에서는 사용자에게 얼마나 많은 사람이 있었는지 물어보고 그 금액을 반환하려고했습니다. 두 번째로 동일한 양의 Person 객체를 만들고 person1, person2, person3이라는 변수에 "i"라는 변수를 사용하고 싶었지만 작동하지 않습니다. 모든 단서?for 루프에서 객체 시작하기

답변

1

정의 클래스의 구성원으로 루프 외부 배열 다음 askingAmount에서 다음

Person[] person; 

당신은 초기화 :

person = new Person[amount]; 

그리고 루프 내부

할 :

person[i] = new Person(); 
1
public static void makingPersons() { 
    Person[] persons = new Person[amount]; 
    for (int i=0 ; i<amount ; i++) { 
     int personNumber=0; 
     persons[i] = new Person(); //<--- The solution 
     System.out.println("person"); 
    } 
} 
0

루프에서 유형 Person의 배열을 초기화하고 다음과 같이 새 인스턴스를 채워야합니다.

public static void makingPersons() { 

    Person[] person = new Person[amount]; 

    for (int i=0 ; i<amount ; i++) { 
     int personNumber=0; 
     person[i] = new Person(); 
     System.out.println("person"); 
    } 
}