这是我到目前为止的代码:
import java.util.Scanner;
public class Whatever{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int number = Integer.parseInt( keyboard.nextLine() );
int continueProgram = 0
while(continueProgram == 0)
{
if (number>= 0 && number <= 32767)
{ do this;
continueProgram++;
}else{
do this;
}
我必须使用integer.parseInt才能使我的其余代码工作,所以我无法改变它。有什么办法只采取整数而不是字母?我的代码产生错误,因为如果我输入一个字母,parseInt将产生红色错误,而不是输出类似&#34的字符串;再试一次。请输入数字&#34;或类似的东西。
答案 0 :(得分:2)
您需要使用try catch这样的
来包围您的parse.intint number = 0; // you need to initialize your variable first
while (true) {
try {
number = Integer.parseInt(keyboard.nextLine());
break; // this will escape the while loop
} catch (Exception e) {
System.out.println("That is not a number. Try again.");
}
}
答案 1 :(得分:1)
试试这个:
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
if(keyboard.hasNextInt()) {
int number = keyboard.nextInt();
}else{
System.out.println("Not an integer number!");
keyboard.next();
}