gpt4 book ai didi

java - 为什么我的 java 数组不允许用户输入每个值?

转载 作者:行者123 更新时间:2023-12-01 16:59:28 25 4
gpt4 key购买 nike

代码应该要求每个数组的三个输入:(ID,然后是名称,然后是主要)。

ID 工作正常,但是当它转到名称时,它会打印出:

请输入学生姓名:请输入学生姓名:

并且该行只允许一个输入。然后它进入专业并再次正常工作。所以我最终得到了 3 个 ID、2 个名字和 3 个专业。

这是我的代码:

package STUDENT;

import java.util.Scanner;

public class StudentDisplayer {

public static void main(String[] args) {

long[]studentId = {11, 22, 33};
String[] studentName = {"Value1", "Value2", "Value3"};
String[] studentMajor = {"Value1", "Value2", "Value3"};
Scanner inReader = new Scanner(System.in);


/* ----------------------------------------------
Print the information in the parallel arrays
---------------------------------------------- */

for (int i = 0; i < studentId.length; i++ ){
System.out.println("Please enter the student's id: ");
studentId[i] = inReader.nextLong();
}

for (int i = 0; i < studentName.length; i++){
System.out.println("Please enter the student's name: ");
studentName[i] = inReader.nextLine();
}

for (int i = 0; i < studentMajor.length; i++){
System.out.println("Please enter the student's major: ");
studentMajor[i] = inReader.nextLine();
}

for (int i = 0; i < studentId.length; i++ )
{
System.out.print( studentId[i] + "\t");
System.out.print( studentName[i] + "\t");
System.out.print( studentMajor[i] + "\t");
System.out.println();
}
}
}

最佳答案

发生的情况是 nextLong() 不会使用换行符 \n (当您按 Intro 时输入该字符) )。因此,在继续您的逻辑之前,您必须先消耗它:

for (int i = 0; i < studentId.length; i++ ){
System.out.println("Please enter the student's id: ");
studentId[i] = inReader.nextLong();
}

inReader.nextLine(); // ADD THIS

for (int i = 0; i < studentName.length; i++){
System.out.println("Please enter the student's name: ");
studentName[i] = inReader.nextLine();
}

注意:您可以阅读我前段时间写的这篇文章:[Java] Using nextInt() before nextLine()

关于java - 为什么我的 java 数组不允许用户输入每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815438/

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