2013-04-09 5 views
1

그래서 학생 이름과 GPA에 대한 사용자 입력을 받아서 단일 arraylist에 정보를 입력하는 프로그램을 만들려고합니다. 꽤 많이, 나는 float과 문자열 변수를 저장하고 사용자 입력을 저장하는 ArrayList을 만들려고합니다. 이 작업을 수행하는 데 생성자를 사용하려고하지만 작동하도록 코드를 가져 오는 데 문제가 있습니다. 여기에 지금까지이 작업은 다음과 같습니다ArrayList를 사용하여 생성자를 호출 할 때

public class BestStudent { 
    static Scanner scanner = new Scanner(System.in); 
    static String name; 
    static float gpa; 

    private class Student { 
    public Student (String n, float g){ 
     name = n; 
     gpa = g; 
    } 
    } 

    public static void findValidictorian(){ 
     ArrayList<Student> validictorian = new ArrayList<Student>(); 
      while (true){ 
       System.out.println("Please enter student name: "); 
       name.add(scanner.next()); 
       System.out.println("Please enter your student's cumulative GPA: "); 
       gpa.add(scanner.nextFloat()); 

       System.out.println("do you want to add another student yes/no?"); 
       String answer = scanner.next(); 

       if (answer.toLowerCase().equals("no")){ 
        break; 
       } 


      } 

    } 


    public static void main(String[] args) { 
     findValidictorian(); 
    } 

} 

나는 내 ArrayList를 내 추가 방법 모두에 오류가 점점 오전, 내가 할 수없는 이유를 내 그림 밖으로의 생활.

+0

아마도 새로운 BestStudent 객체를 만들고, 스캐너에서 읽은 내용으로 필드를 설정 한 다음, *** 목록에 추가하십시오. ? – Perception

+0

'name'과'gpa' 필드는 외부 클래스가 아닌 내부 클래스 자체에 저장해야합니다. – gparyani

답변

3

validictorianArrayList,하지만 당신은 하지ArrayList들입니다 gpaname에 추가하려는, 당신은 결코 validictorian에 추가되지 않습니다. 난 당신이 그들에게하지 add 요소를 할 수있는, 당신이 원하는 것은

name = scanner.next(); 
... 
gpa = scanner.nextFloat(); 
validictorian.add(new Student(name, gpa)); 
+0

이것은 정확하게 잘못되었습니다. 나는 방금 Arraylists를 배웠고, 소년은 어리 석다. 감사! – penguinteacher

0

namegpa 배열 목록이 아닌 더처럼 생각합니다. 눈에 유일한 ArrayList은 (. 원문) validictorian라고 어쨌든 있습니다 (ArrayList 유형 Object를 사용하는 매개 변수가있는 경우에 잘, 당신은 추가 할 수있는 ArrayList에 다른 유형의 요소를 추가 할 수 없습니다,하지만 그건 나쁜 연습).

validictorian에는 Student 유형의 개체가 포함되어 있습니다. 당신이 모든 것을하기 위해 의도 한 것은 이것입니다 :

System.out.println("Please enter student name: "); 
String aName = scanner.next(); 
System.out.println("Please enter your student's cumulative GPA: "); 
float aGpa = scanner.nextFloat(); 
validictorian.add(new Student(aName, aGpa)); 
관련 문제