2017-04-25 89 views
-1

這個程序應該允許用戶輸入一個學生的名字和得分10次,並輸出平均值和學生的名字,低於和大於/等於平均。當它到達輸出高於/低於平均分數的學生的程序點時,它將循環執行,而不是僅打印出所有名稱一次。我究竟做錯了什麼?無法打印出我的輸出語句一次沒有循環

謝謝你`進口java.util.Scanner;

public class Grades{ 

    public static void main(String[] args){ 

    //create a keyboard representing the scanner 
     Scanner console = new Scanner(System.in); 

    //define variables 
     double [] score = new double[10]; 

     String [] name = new String[10]; 
     double average = 0.0, sum = 0.0, studentAverage = 0.0, highestScore = 0.0, lowestScore = 0.0; 


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

     System.out.println("Enter the student's name: "); 
     name[i] = console.next(); 
     System.out.println("Enter the student's score: "); 
     score[i] = console.nextDouble(); 

     sum += score[i]; 

     }//end for loop 

     //calculate average 
     average = sum/score.length; 

     System.out.println("The average score is: " + average); 


     int highestIndex = 0; 

     for(int i = 1; i < score.length; i++){ 

     if(score[highestIndex] < score[i]){ 

      highestIndex = i; 

     } 

     if(score[i] < average){ 
      System.out.print("\nNames of students whose test scores are less than average: " + name[i]); 
     } 

     if(score[i] >= average){ 
      System.out.print("\nNames of students whose test scores are greater than or equal to average: " + name[i]); 
     } 


     }//end for loop 

    }//end main 

}//end clas 

`

+0

嗯,你打電話給'System.out.print(「\ n學生的名字...」)'在內部循環,因此「它在一個循環中這樣做」。您可能希望先將名稱收集到列表中,然後將其打印出來(並打印您可能想要使用循環的列表元素,只需調用'System.out.print(「\ n學生名稱...:」) ; for(String name:list){/ *在這裏打印名字* /}'。 – Thomas

+0

我想你需要重新說出你的問題是什麼 –

回答

0

修改你的循環這樣的:

System.out.print("Names of students whose test scores are less than average: "); 
for(int i = 1; i < score.length; i++){ 
    if(score[i] < average){ 
     System.out.print(name[i]); 
    } 
} 

System.out.print("Names of students whose test scores are greater than or equal to average: "); 
for(int i = 1; i < score.length; i++){ 
    if(score[i] >= average){ 
     System.out.print(name[i]); 
    } 
} 

根據您目前的代碼,你要打印出包含您在每次循環迭代文本在同一行。使用修改後的代碼,您只需打印一次,然後輸入名稱。

+0

非常感謝 – user7613788