gpt4 book ai didi

java - 循环->数组输出

转载 作者:行者123 更新时间:2023-11-29 05:04:19 24 4
gpt4 key购买 nike

我正在编写一个循环来填充一个数组。我想我已经编写好了代码,但是当我通过 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年级:

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

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

最佳答案

您需要使用 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 时,Tom 在该答案下的评论中提到(); 程序运行正常,但它弄乱了数组的值。

关于java - 循环->数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30955555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com