2

我正在尝试编写一个 if/else 来测试用户输入的整数。如果他们输入一个 int,程序就会继续。如果他们输入任何其他内容,程序会生成一条错误消息,要求输入正确。这是在球场的任何地方吗?

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) {  
4

3 回答 3

6

尝试以下方法来验证您的输入:

Scanner.hasNextInt()

int itemChoice =0;
while(true){
    if(keyboard.hasNextInt()){    
        itemChoice = keyboard.nextInt();    
        // Do something.
        break;
    }
    else{    
        System.out.print("Not a valid choice Try again");
        continue;

    }

}
于 2013-05-06T15:23:13.050 回答
1

您的问题是您正在将int[](int array) 与a 进行比较int

itemChoice != foo  

应该:

boolean tmp = false;
for (int i=0; i < foo.length; i++) {
    if (foo[i] == itemChoice) {
       tmp = true;
    }
}
if (tmp) {
    System.out.print("Valid choice. You picked " + itemChoice);
}  
else {  
    System.out.print("Not a valid choice");  
}  
于 2013-05-06T15:30:10.990 回答
0

你为什么不把你的代码放在一个循环中,比如while

那么:

while (my input is not a number) {
 //Here I do the block of code.
 //I can implement an if to handle the error messages
}

我没有过多地使用 Scanner 类或有任何类似的要求,但也许它可以提供帮助。此致。

于 2013-05-06T15:30:07.957 回答