2013-04-25 72 views
1

所以首先,如果我要求你做我的功課時出現這種情況,對不起,只是我你不是,這個問題只涉及到一個小小的方面正在製作的整個程序...換句話說,這是不完成的。如何在循環中列出多維數組值

我會問我的老師,但它的在線課程。所以我會問我的朋友們的建議,但我是學校參加計算機科學課程的唯一孩子。 (這是一所小學校)

反正這個程序完成後,會讓老師輸入一個學生名單,每個學生四個年級。最後,我會添加一些代碼,讓老師找到每個學生的平均等等等。

但是目前我只在上市學生的過程中。哪裏出現小問題...

每次我列出一個學生(他們的姓氏和名字)以及四個考試成績,都會很好地輸出。然而,當我輸出第二名學生的名字不同而且考試成績不同時,會輸出不同的名字......但是前一名學生的考試成績。

Ex。

約翰·史密斯:67 68 57 87

李四:67 68 57 87(即使它應該李四:54 68 75 91)

而且很顯然這是一個問題......因爲所有學生沒有完全相同的成績......曾經..

下面

好的代碼...

public class StudentGradesView extends FrameView { 
    int [][] aryStudent = new int [15][4]; //[15] being number of students and [4] being test scores... 
    String[] studentNames = new String[15]; // I'm thinking this is might unnecessary now...but we'll see 
    int numOfStudents = 0; //starting number of students at 0.... 

    int marks = 0; 

    int test1; 
    int test2; 
    int test3; 
    int test4; 

    public StudentGradesView(SingleFrameApplication app) { 
     //unimportant...just stuff added for GUI.. 
    } 

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { 
     //test1Field through test4Field are the test scores.... 
     aryStudent[numOfStudents][0] = Integer.parseInt(test1Field.getText()); 
     aryStudent[numOfStudents][1] = Integer.parseInt(test2Field.getText()); 
     aryStudent[numOfStudents][2] = Integer.parseInt(test3Field.getText()); 
     aryStudent[numOfStudents][3] = Integer.parseInt(test4Field.getText()); 

     StringBuilder sb = new StringBuilder(); 

     for (int x=0; x < numOfStudents ; x++) { 
      sb.append(firstNameField.getText() + " " + lastNameField.getText()); 
      for (int y=0; y < 4; y++) { 
       sb.append(" " +aryStudent[x][y]); 
      } 
      sb.append("\n"); 
     } 
     studentListField.setText(sb.toString()); 
     numOfStudents ++; 
    }           
} 
+0

如何將'numOfStudents'和'x'的值添加爲調試輸出,以便更好地跟蹤問題。 – Sentry 2013-04-25 15:57:25

+0

您不在任何地方存儲學生姓名。每次他們按下按鈕時,都會獲得當前的學生姓名,但似乎並未保存。它只是將其與其他數據一起寫入studentFieldList,但每次按下按鈕時都會覆蓋它。 – Jason 2013-04-25 18:00:02

回答

0

首先,你要

for (int x=0; x<= numOfStudents; x++) 

或者當numOfStudents = 0時,你將永遠不會進入循環。

此外,addButtonActionPerformed有一個for循環,其中包含您給我們的代碼?否則,似乎每次進入該方法時,numOfStudents都將爲0,當您退出時它將爲1,但代碼僅針對numOfStudents = 0執行。我是否錯過了某些內容?

+0

有一個「numOfStudents ++;」在循環之後,我相信這會改變它最初等於0的方式嗎?此外,在第一個循環中添加了等號也解決了我的測試分數問題,但是現在它爲每個學生保留相同的名稱,但不同的成績。如果我要使用我的字符串「String [] studentNames = new String [15];」並添加studentNames [numOfStudents] = firstNameField.getText()+「」+ lastNameField.getText();「」我的循環中的某處,你認爲這會解決新名稱問題嗎? – Que 2013-04-25 15:54:45

+0

條件x <= numOfStudents將在x = 15時拋出ArrayIndexOutOfBoundsException。爲了更安全你可以有(x <= numOfStudents && x <15) – jittakal 2013-04-25 16:19:54

+0

你在哪裏實際填充名字的aryStudent? – Melanie 2013-04-25 16:20:51