这是我学习Java的第一个项目。 游戏看起来不错,但我需要得到输入检查,如果它是肯定的整数等。当我试图检查它与Int,但这“打印行”打印它自己再次做了函数后,它必须做的打印。我请求你的理解,因为我刚刚学习它(开始这周)。
我说的是这部分:
if(scanner.hasNextInt()){
choiceStr1=scanner.next();
choice_1= Integer.parseInt(choiceStr1);
}
else {
System.out.println(input);
space = enterScanner.nextLine();
townGateRevisited();
}
完整代码:
https://pastebin.com/rc5mcef4
要检查用户输入是否为整数,只需使用try
块中的scanner.NextInt();
方法,如果不是int,则捕获InputMismatchException
。
try{
int choiceStr1=scanner.nextInt();
}catch(InputMismatchException e){
//do something here, this block will be skipped if user input is int
}
我给你一个非常基本的例子,我在第一次学习这门语言时编写了代码。 提醒你,这是非常基本的,还有其他的方法! 但这应该可以很好地向您展示如何循环,同时检查您的输入是否正确
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
Scanner scan = new Scanner(System.in);
String enteredNumber = "";
do {
System.out.println("enter a number");
enteredNumber = scan.nextLine();
} while (!isNumber(enteredNumber));
}
private static boolean isNumber(String isNumber) {
for (int i = 0; i < isNumber.length(); i++) {
if (!isDigit(isNumber.charAt(i))) {
return false;
}
}
return true;
}
private static boolean isDigit(char isDigit) {
for (int i = 0; i < 10; i++) {
if (isDigit == i + 48) {
return true;
}
}
return false;
}
}
这不需要try-catch,它使用ascii值检查输入。 这就是为什么我使用nextLine()而不是nextInt()。
快乐的编码,继续问问题/谷歌!