在不循环的情况下打印我的输出语句时遇到麻烦



该程序应该允许用户输入学生的姓名并得分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

`

像这样修改循环:

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

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

最新更新