2015-10-13 73 views
0

所以,我希望sArr在if之後有一個數字,並且每次循環結束時都會遞增。我不知道我做錯了什麼,有人可以解釋嗎?用於創建具有遞增名稱的對象的數組

import java.util.*; 
public class StudentTest { 


    public static void main(String[] args){ 
    Scanner in = new Scanner(System.in); 
    String id, name, gender, address; 
    Student[] sArr = new Student[4]; 
    int age; 
    for(int i=0; i>=sArr.length(); i++){ 
     System.out.println("student id."); 
     id = in.nextLine(); 
     in.nextLine(); 
     System.out.println("Sutdent name."); 
     name = in.nextLine(); 
     in.nextLine(); 
     System.out.println("Gender."); 
     gender = in.nextLine(); 
     in.nextLine(); 
     System.out.println("Address."); 
     address = in.nextLine(); 
     in.nextLine(); 
     System.out.println("Age"); 
     age = in.nextInt(); 

     Student sArr[i] = new Student(id, name, gender, age, address); 
     s2.display(); 
    } 
    } 
} 

此代碼給了我這些錯誤:

--------------------Configuration: <Default>-------------------- 
C:\StudentTest.java:31: error: ']' expected 
     Student sArr[i] = new Student(id, name, gender, age, address); 
        ^
C:\Users\Bart\Desktop\Bart Kosinski_2886295_Assignment01\StudentTest.java:31: error: illegal start of expression 
     Student sArr[i] = new Student(id, name, gender, age, address); 
        ^
2 errors 

Process completed. 

回答

1

變化

Student sArr[i] = new Student(id, name, gender, age, address); 

sArr[i] = new Student(id, name, gender, age, address); 

Student sArr[i]是(無效)數組聲明。您之前已經聲明瞭陣列(在Student[] sArr = ...中)。現在您想要將一個Student引用分配給該數組的索引。

這將處理編譯錯誤。你應該修復的另一件事是循環的條件。

for(int i=0; i>=sArr.length(); i++) 

應該

for(int i=0; i<sArr.length(); i++) 

否則循環將永遠不會被執行。

相關問題