在没有循环的情况下打印输出语句时遇到问题

时间:2017-04-25 14:30:36

标签: java

该程序应该允许用户输入学生的姓名并得分10次,并输出平均值和学生的分数。名称低于和大于/等于平均值​​。当它到达程序时,它输出得分大于/小于平均值的学生,它在循环中这样做,而不是只打印出所有名称一次。我做错了什么?

谢谢`import 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

`

1 个答案:

答案 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]);
    }
}

使用当前代码,在每次循环迭代时打印出包含文本的同一行。使用修改后的代码,您只需打印一次,然后输入名称。