gpt4 book ai didi

java - 为什么我的 for 循环在使用 (scanner).nextLine(); 时一次打印 2 个提示

转载 作者:行者123 更新时间:2023-11-30 03:29:27 25 4
gpt4 key购买 nike

我的 while 或 for 循环是否偶然出现问题,或者我遗漏了什么?第一次运行效果很好,但第二次我得到了这个:

Enter course NAME: class name
Enter course HOURS: 4
Enter course GRADE: 4.0
You have entered class: jeff graves, class hours: 4 and, class grade 4.0
Do you want to continue:
y
Enter course NAME: Enter course HOURS:

使用 (scanner).next(); 工作得很好,但是我只能从用户那里获取一个单词,并且当它滚动时,它会从 nextInt 抛出一个错误。

   public class GetGrades { //open class GetGrades

public static void main(String[] args) {
/**creating new instance of scanner named input to read user input*/
Scanner input = new Scanner(System.in); // create new instance of scanner object
boolean repeat = true; //boolean value for while loop holding array input
String s; // create string to store user input value for exiting loops
/** create 3 arrays to store course name, hours, and grades*/
String[] name = new String[20]; //type string array for class name
int[] hours = new int[20]; // type int array for class hours
float[] grade = new float[20]; //type float array for class grade


outerloop: // set break point for nested for loops exit on user input
while(repeat != false) {// while loop with boolean value to let user exit array input
for (int i=0; i<name.length; i++) { //for loop for name array

System.out.print("Enter course NAME: "); //prompt user for input
name[i] = input.nextLine(); //read next line value and store in array name
System.out.print("Enter course HOURS: "); //prompt user for input
hours[i] = input.nextInt(); //read the next int and store in array hours
System.out.print("Enter course GRADE: "); //prompt user for input
grade[i] = input.nextFloat(); //read the next float value and store in array grade

/**Print line to console summing um what the user has entered*/
System.out.println("You have entered class: " + name[i] + ", class hours: " + hours[i] +
" and, class grade " + grade[i]);

/**prompt user if wanted to enter more grades, break loop on n or N*/
System.out.println("Do you want to continue:");
s = input.next();
if ( s.equals("y") || s.equals("Y")) { //open if statement
repeat = true;
} else { //close if and open else
break outerloop;
} //close else statement


}//close for loop with i as count
}//close while

最佳答案

input.next() 将读取下一个单词。 input.nextLine() 将一直读取,直到您下次按 Enter 键。

这意味着当您输入“y”并按回车键时,您既输入了单词“y”,也输入了下一个回车键,同时填写了两个提示并导致写入下一个提示.

当您要求继续时,您只需将 next() 替换为 nextLine() 即可:

        System.out.println("Do you want to continue:");
s = input.next();

变成了

        System.out.println("Do you want to continue:");
s = input.nextLine();

从而读取“y”和回车键。下一个提示现在可以自由接受新输入。

关于java - 为什么我的 for 循环在使用 (scanner).nextLine(); 时一次打印 2 个提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425515/

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