循环->数组输出

Loop->Array Output

我正在编写一个循环来填充一个数组。我想我已经记下了编码,但是当我 运行 通过 Java 编译代码时,它并没有在命令提示符中正确显示。

代码如下:

import java.util.Scanner;
import java.io.*;
public class Pr42
{
    public static void main(String[]args) throws IOException
{
    int k,m,g;
    String n;
    //double g;
    Scanner input1=new Scanner(System.in);
    String[]Name=new String [5];
    double[]Grade=new double[Name.length];
    k=0;
    while (k<Name.length)
        {
        m=k+1;
        System.out.print("Enter the name of student "+m+": ");
        Name[k]=input1.nextLine();
        System.out.print("");
        System.out.print("Please enter the grade of student "+m+": ");
        Grade[k]=input1.nextInt();
        k++;
        }
    }
}

命令提示符中的输出如下:

输入学生1的姓名:

请输入学生1的年级:

请输入学生2姓名: 请输入学生2年级:

问题是关于第二个学生的那一行。

我在代码中做错了什么以获得这样的输出?

问题在于:Grade[k] = input1.nextInt(); 不读取行尾或数字后的任何内容。

尝试在 Grade[k]=input1.nextInt(); 之后放置一个 input1.nextLine(); 应该可以解决问题:

while (k<Name.length)
{
        m=k+1;
        System.out.print("Enter the name of student "+m+": ");
        Name[k]=input1.nextLine();
        System.out.print("");
        System.out.print("Please enter the grade of student "+m+": ");
        Grade[k]=input1.nextInt();
        input1.nextLine();
        k++;
}

您需要确定名称在下一行输入 Name[k] = input1.nextLine();

int k, m, g;
String n;
//double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
    m = k + 1;
    System.out.print("Enter the name of student " + m + ": ");
    Name[k] = input1.nextLine();
    System.out.print("");
    System.out.print("Please enter the grade of student " + m + ": ");
    Grade[k] = input1.nextDouble();
    input1.nextLine();
    k++;
}

已编辑: 正如汤姆在这个答案下的评论中提到的那样,当您使用 Name[k] = input1.nextLine(); 而不是 input1.nextLine(); 程序时,它可以正常工作,但它搞砸了数组的值。

Scanner 的 nextInt 不读取 "new line" 字符。
有两种方法可以修复它。
1. 在 input1.nextInt(); 之后调用 input1.nextLine(); 忽略你在这里得到的东西,它只是让它转到下一行。

Grade[k] = input1.nextInt();
input1.nextLine();

2。请致电 input1.nextLine(); 获取成绩。 你得到的 String 可以转换为 int 并保存在 Grade[k].

String str = input1.nextLine();
Grade[k] = Integer.parseInt(str);

这个有效:

public static void main(String[] args) throws IOException {
    int k, m, g;
    String n;
    // double g;
    Scanner input1 = new Scanner(System.in);
    String[] Name = new String[5];
    double[] Grade = new double[Name.length];
    k = 0;

    while (k < Name.length) {

        m = k + 1;
        System.out.print("Enter the name of student " + m + ": ");
        Name[k] = input1.nextLine();
        System.out.print("Please enter the grade of student " + m + ": ");
        Grade[k] = input1.nextInt();
        input1.nextLine();
        k++;
    }
}

推荐你看一下this question,你的疑惑一定会得到解答。摘自post中给出的答案:

Scanner#nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.