gpt4 book ai didi

java - 分配双通扫描仪不会读取第一个输入

转载 作者:行者123 更新时间:2023-12-01 18:02:06 26 4
gpt4 key购买 nike

我目前正在为一个类(class)编写一个程序。目标是能够让用户输入一个整数,并使用输入的大小初始化一个数组。然后,程序会提示用户输入每个数组槽位(等级如下所示)。当输入无效时,我们还应该使用 while 循环。我的问题是,当要求一年级时,它需要两个数字输入才能循环。

import java.util.Scanner;

public class ForWhile {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int arraySize;

System.out.print("Gpa Calculator");
System.out.print("\nEnter total classes: ");
arraySize = scanner.nextInt();

double[] grades = new double[arraySize];

for (int i = 0; i < arraySize; i++) {

System.out.println("Enter grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();

while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
}
}
}

这是我目前所写的,但在控制台中我期望输入 2:

GPA Calculator
Enter grade for class 1: 90
Enter grade for class 2: 85

要取得进展,需要做的是:

GPA Calculator
Enter a grade for class 1: 90
90
Enter a grade for class 2: 85

我尝试过使用scanner.hasNextLine(),但不太成功,我错过了什么?我还认为我的 while 循环条件没有正确循环,任何输入将不胜感激!

最佳答案

您当前正在检查读取double后是否存在要读取的double。这个,

grades[i] = scanner.nextDouble();

while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}

应该是

while (!scanner.hasNextDouble()) {
scanner.nextLine(); // consume the thing that isn't a double
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
}
grades[i] = scanner.nextDouble();

关于java - 分配双通扫描仪不会读取第一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60611709/

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