有没有办法测试字符串的int? (JAVA)

时间:2013-05-06 15:21:18

标签: java

我正在尝试编写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) {  

3 个答案:

答案 0 :(得分: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;

    }

}

答案 1 :(得分:1)

您的问题是您正在将int[](int数组)与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");  
}  

答案 2 :(得分: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类或有任何类似的要求,但也许它可以提供帮助。最好的问候。