我的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
答案 0 :(得分:2)
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”和输入。现在,下一个提示可以自由接受新输入。
答案 1 :(得分:0)
输入成绩时,例如12.3并输入“input.nextFloat();”只会选择“12.3”而不是“输入”,所以“输入”将由下一个扫描仪拍摄。
在我看来,
首先,将“s = input.next()”更改为“s = input.nextLine()”,但它将采用先前扫描仪的“enter”“grade [i] = input.nextFloat();” ,所以,第二,把它作为条件放入while循环。像这样
while((s = input.nextLine()).equals("")) {}
因此,它不会停止直到获得期望输入。
试试这个..
System.out.print("Do you want to continue:");
while((s = input.nextLine()).equals("")) {}
if (s.equals("y") || s.equals("Y")) { // open if statement
repeat = true;
} else { // close if and open else
break outerloop;
} // close else statement