我想写一个if/else来测试整数的用户输入。如果他们输入一个int,程序就会继续。如果他们输入了其他内容,程序会产生一个错误消息,要求输入正确的信息。这是在球场的任何地方吗?有没有办法根据字符串测试一个int? (Java)
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int [] foo;
foo = new int[3];
foo[0]=1;
foo[1]=2;
foo[2]=3;
System.out.print("Make a choice between 0 and 2: ");
int itemChoice = keyboard.nextInt();
if (itemChoice != foo) {
System.out.print("Not a valid choice");
}
else {
System.out.print("Valid choice. You picked " + itemChoice);
}
}
}
我得到这个错误:
required: int
found: boolean
test.java:17: error: incomparable types: int and int[]
if (itemChoice != foo) {
你试过了吗?那么['Integer.parseInt()'](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String))呢? – thegrinner 2013-05-06 15:23:13
@thegrinner到目前为止我没有办法。我的编者说我的使用不对等是有问题的。 – 2013-05-06 15:26:27
@TyGivens:将来,将(编译器)的错误消息复制/粘贴到您的问题中。 – 2013-05-06 15:27:29