gpt4 book ai didi

java - 有没有办法根据字符串测试 int ? ( java )

转载 作者:行者123 更新时间:2023-12-02 05:33:27 25 4
gpt4 key购买 nike

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

最佳答案

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

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;

}

}

关于java - 有没有办法根据字符串测试 int ? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16401904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com