<문제 사항>
컴파일시 p2.information()에서 오류가 난다.
System.out.println("2번 문제");
Scanner sc = new Scanner(System.in);
ArrayList<Employee> p2 = new ArrayList<>();
while(true) {
System.out.print("이름 : ");
String name = sc.nextLine();
System.out.print("나이 : ");
int age = sc.nextInt();
System.out.print("신장 : ");
double height = sc.nextDouble();
System.out.print("몸무게 : ");
double weight = sc.nextDouble();
System.out.print("급여 : ");
int salary = sc.nextInt();
sc.nextLine();
System.out.print("부서 : ");
String dept = sc.nextLine();
p2.add(new Employee(name,age,height,weight,salary,dept));
System.out.print("계속 추가하시겠습니까? Y/N ");
String str = sc.nextLine().toUpperCase();
if(str.equals("Y")) {
continue;
} else {
System.out.println("이용해주셔서 감사합니다.");
break;
}
}
System.out.println("결과 ");
System.out.print(p2.information());
<에러코드> The method information() is undefined for the type ArrayList<Employee>

ArrayList<Employee>에는 information()이 정의되어 있지 않다.는 구문인 것 같은데 강제로 실행시키면 다음와 같은 문구가 콘솔창에 출력된다.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method information() is undefined for the type ArrayList<Employee>
at com.hw1_1.run.Run.main(Run.java:68)
<위의 코드가 틀렸던 이유>
말그대로 p2는 ArrayList기 때문에 거기엔 information 같은 메소드는 없다.
<해결방안>
information메소드는 Employee 클래스에 있기 때문에 Employee객체.imformation() 이렇게 해야한다.
Employee객체는 ArrayList에 각 인덱스에 담겨있으니 해당 리스트에 get메소드로 인덱스에 접근하고 information 메소드 호출해야한다.
안되는 줄 알았던 코드였는데 다시 해보니 정상적으로 실행 되었다.
System.out.println("2번 문제");
Scanner sc = new Scanner(System.in);
ArrayList<Person> p2 = new ArrayList<>();
while(true) {
System.out.print("이름 : ");
String name = sc.nextLine();
System.out.print("나이 : ");
int age = sc.nextInt();
System.out.print("신장 : ");
double height = sc.nextDouble();
System.out.print("몸무게 : ");
double weight = sc.nextDouble();
System.out.print("급여 : ");
int salary = sc.nextInt();
sc.nextLine();
System.out.print("부서 : ");
String dept = sc.nextLine();
p2.add(new Employee(name,age,height,weight,salary,dept));
System.out.print("계속 추가하시겠습니까? Y/N ");
String str = sc.nextLine().toUpperCase();
if(str.equals("Y")) {
continue;
} else {
System.out.println("이용해주셔서 감사합니다.");
for(int i=0; i<p2.size();i++) {
System.out.println(p2.get(i).information());
}
break;
}
}
<결과값>
2번 문제
이름 : 마우수
나이 : 20
신장 : 140
몸무게 :30
급여 : 300
부서 : 빠비
계속 추가하시겠습니까? Y/N y
이름 : 도동개
나이 : 29
신장 : 160
몸무게 :60
급여 : 400
부서 : 빠비
계속 추가하시겠습니까? Y/N n
이용해주셔서 감사합니다.
이름은 마우수이고, 나이는 20살이야. 키는 140.0cm이고, 몸무게는 30.0kg 이야급여는 300만원이고, 부서는 빠비이야 만나서 반가워
이름은 도동개이고, 나이는 29살이야. 키는 160.0cm이고, 몸무게는 60.0kg 이야급여는 400만원이고, 부서는 빠비이야 만나서 반가워
'🚨 Error > JAVA' 카테고리의 다른 글
[JAVA] Collection _ 도서 검색용 View 메소드 작성 (0) | 2021.03.19 |
---|---|
[JAVA] Collection 실습 문제 2. 존재하는 도서가 없습니다. (0) | 2021.03.09 |
[JAVA] 박수박수 문제 (0) | 2021.03.03 |
[JAVA] 상속 구조에서의 출력문 오류 (0) | 2021.03.02 |
[JAVA] controller에서 나오는 결과 값의 변수명을 list가 아닌 seachList으로 넣고싶다. (0) | 2021.02.26 |
댓글