2013-04-09 113 views
1

所以我試圖創建一個程序,它接收用戶輸入的學生姓名和GPA,並將信息輸入到一個數組列表中。非常多,我試圖創建一個ArrayList,它同時存儲一個float和一個字符串變量,並存儲用戶輸入。我試圖使用構造函數來完成此任務,但我無法讓我的代碼正常工作。這是我到目前爲止有:使用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 2013-04-09 21:29:10

+0

您應該將'name'和'gpa'字段存儲在內部類中,而不是存儲在外部類中。 – gparyani 2013-04-09 21:30:04

回答

3

validictorianArrayList,但你要添加到gpaname,這是ArrayList s,而你從不添加到validictorian。我想你想要的東西更像是

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

這正是錯誤的地方。我今天剛剛學會了Arraylists,而男孩我覺得很愚蠢。謝謝! – penguinteacher 2013-04-09 21:32:03

0

namegpa不是數組列表,你不能add元給他們。在望唯一ArrayList被稱爲validictorian(原文如此。)反正,你不能在不同類型的元素添加到ArrayList(當然,你可以添加它們,如果ArrayList是參數化使用類型Object,但是這是一個不好的練習)。

請注意,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));