-5

这是代码:

import java.util.Scanner;
public class Array2 
{
  static Scanner input = new Scanner ( System.in );

  public static void main ( String [] args )
  {
    String [] studentNames = new String [5];
    student_Names ( studentNames );
  }

  public static void student_Names ( String [] studentNames )
  { 
    for ( int x = 0; x < studentNames.length; x++ )
    {
      System.out.printf( "\nStudent %d name : ", x+1);
      studentNames[x] = input.nextLine();
      student_Scores();
    }
  }

  public static void student_Scores ()
  {
    double [] studentScores = new double [4];
    int x;
    for ( x = 0; x < studentScores.length; x++ )
    {
      System.out.printf( "\nEnter marks for test %d: ",x+1 );
      studentScores[x] = input.nextDouble();
    }
    average_Scores( studentScores );
  }

  public static void average_Scores( double [] a )
  {
    int i;
    double sum, average;
    for ( i = 0, sum = 0; i < a.length; i++ )
    {
      System.out.printf("Marks Test %d : %.2f\n", i+1, a[i]);
    }

    for ( i = 0, sum = 0; i < a.length; i++ )
    {
      sum = sum + a[i];
    }
    average = sum / a.length;
    student_Grades ( average );
    System.out.printf("\nAverage Score : %.2f", average);
  }

  public static void student_Grades ( double b )
  {
    String c = "";
    if ( b > 0 && b < 60)
      c = "F";
    if ( b >= 60 && b < 70)
      c = "D";
    if ( b >= 70 && b < 80)
      c = "C";
    if ( b >= 80 && b < 90)
      c = "B";
    if ( b >= 90 && b <= 100)
      c = "A";
    System.out.printf("\nGrade         : %s", c);
  }
}

这是执行时的输出:

Student 1 name : sss

Enter marks for test 1: 12

Enter marks for test 2: 23

Enter marks for test 3: 34

Enter marks for test 4: 45
Marks Test 1 : 12.00
Marks Test 2 : 23.00
Marks Test 3 : 34.00
Marks Test 4 : 45.00

Grade         : F
Average Score : 28.50
Student 2 name : 
Enter marks for test 1: 
4

1 回答 1

0

您的问题可以在方法中找到student_Names;代替:

studentNames[x] = input.nextLine();

采用

if(x>0) input.nextLine();
studentNames[x] = input.nextLine();

您的问题来自 Java 错误地认为用户已经输入了下一个名称;input.nextLine();基本上把这个输入扔掉,让事物恢复到它们的自然状态。

但是,由于姓名输入对第一个学生工作正常,因此if(x>0)有必要使用该语句以使其仅适用于其余学生姓名。

于 2012-11-29T00:37:43.333 回答