在学习.Net之后,我决定亲自动手学习Java。
在重新创建我的Hello World之后,我决定制作一个可能用途有限的程序。它似乎运行得很好,直到我给它选项重新启动input.nextline()
似乎完全被忽略,它只是无限循环。下面我提交我的小程序,旨在帮助我女儿的数学。
package sndgrdmth;
import java.util.Scanner;
import java.util.Random;
public class sndgrd {
public static void main(String[] args) {
Boolean bool = true;
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (bool == true) {
System.out.println("Enter the highest number to add with:");
String str = input.nextLine();
while (isNum(str) == false) {
System.out
.println("Not a valid number.\rEnter your high number:");
str = input.nextLine();
}
int i = Integer.parseInt(str);
int counter = 0;
int topCounter = 5;
while (counter < topCounter) {
int a = rand.nextInt(i);
int b = rand.nextInt(i);
System.out.println(a + " + " + b + " = ?");
int j = input.nextInt();
if (j == a + b) {
++counter;
System.out.println("Correct Answer " + counter + " of "
+ topCounter + "!!!");
} else {
--counter;
System.out.println("Incorrect Answer " + a + " + " + b
+ " = " + (a + b) + "\rLose one point.");
}
}
System.out.println("Congrats! You Win! Do you want to play again? (Y/N)");
//The next line seems to get skipped.
String repeat = input.nextLine();
if ((repeat == "N") || (repeat == "n")) {
bool = false;
}else{
bool = true;
}
}
input.close();
}
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
} catch (NumberFormatException e) {
ret = false;
}
return ret;
}
}
答案 0 :(得分:1)
而不是使用nextLine()
使用next()
,这是因为在使用input.nextInt();
得到测试的最后一个int后,它只会使用int
而不是'\n'
input.nextLine();
因此,当您致电nextLine()
时,它将消耗'\ n',然后继续下一段代码。
<强>溶液强>
将您的所有next()
更改为{{1}}。