2016-01-29 176 views
-2

我想創建一個數組,它將允許我使用存儲的元素來創建另一個單獨的數組。是否可以用數組聲明一個數組?

這是我到目前爲止有:

Scanner reader = new Scanner(System.in); 

//variables 
int NumberOfStudents; 

System.out.print("How many students are in the class?: "); 
NumberOfStudents = reader.nextInt(); 
reader.nextLine(); 
//objects 
String [] names = new String[NumberOfStudents];  //Creates an array based on the number of students 

//input 
for (int i = 0; i < NumberOfStudents; i++){ 
    System.out.print("What is student number " + (i+1) + "'s name?: "); 
    names[i] = reader.nextLine(); 
    double [] names[i] = new double [5]; //declares each student name as a separate array 
} 

在此,我也行double [] names[i] = new double [5];,應採取names[]陣列的價值指數i的,把它變成長度5的陣列。因此,如果names[1] = Ann,它應該創建一個長度爲5的數組Ann[]。但是,它會引發表達式錯誤的非法開始。

我試圖使用一個臨時變量,以協助宣佈多個陣列過,但是我獲得了更多的錯誤表達旁邊的非法啓動。因此顯然你不能使用數組或變量來聲明其他數組。

有沒有辦法解決這個問題,而不使用多維數組?

在此先感謝。

+3

如果您講解五行陣的目的,我們也許能夠給你一些選項。 –

+0

@AMACB提問者特別試圖避免使用多維數組。 –

+0

如果你能解釋你認爲這個陳述的作用會有多大幫助:'double [] names [i] = new double [5];',特別是你明白'double'的意思。 –

回答

2

要做到這一點,而不多維數組是通過創建Students類的數組,將舉行對學生的信息,如firstNamelastNamegrade

Student類:

public class Student(){ 

    String fname, lname; 
    int grade; 

    public Student(String name){ 
     String[] firstLast = name.split(" "); 
     fname = firstLast[0]; 
     if(firstLast.length>1) lname = firstLast[1]; 
    } 

    public string setFName(String nameOfStudent){ 
     fname = nameOfStudent; 
     return fname; 
    } 

// rest of code implementation 
} 

在當前類:

Student array[] = new Student[NumberOfStudents]; 

那麼你可以使用的想法,你已經有

for (int i = 0; i < NumberOfStudents; i++){ 
    System.out.print("What is student number " + (i+1) + "'s name?: "); 
    String studentName = reader.nextLine(); 

    array[i] = new Student(studentName); // initialize the array 
} 
+1

這實際上是我想到的答案。但是,不要忘記,初始化數組後,您仍然需要初始化數組中的每個元素。您的代碼目前會拋出'NullPointerException's –

+0

好的結果,我更新了答案@CalvinP。 –

+0

還缺少一個構造函數。在OP的情況下,他們可能會想要一個名稱爲String的參數(或2個字符串作爲第一個,最後一個) –

0

它看起來像您嘗試使用剛剛輸入的變量名字符串創建一個數組,像這樣:

double[] <student_name> = new double[5]; 

不幸的是(或者幸運),你不能創建從另一個的內容變量。

相反,您可以執行下列操作之一:

  • 做什麼凱文眉在他的回答已經提出並使用Student類。
  • 使用Map<String, Double[]>,像吉姆·加里森建議,有關你的問題的意見。使用2維數組。

如果你想嘗試一個2維數組,你應該;在你當前的類中,定義一個2維數組。

double[][] studentInfo = new double[NumberOfStudents][5]; 

然後你可以引用數組是這樣的:

studentInfo[i][j] = aDoubleNumber; 
相關問題