【问题标题】:How to tell my if-statement to only accept integers?如何告诉我的 if 语句只接受整数?
【发布时间】:2012-09-28 16:09:01
【问题描述】:

我希望我的程序告诉用户,如果他输入了一个非整数,他应该再试一次,而不是像现在这样终止整个 main 方法。问题部分伪代码:

int integer = input.nextInt();
If (user types in a non-integer) { 
  ("you have entered a false value, please retry");
  then let's user enter int value
else {
  assign nextint() to integer and continue
}

【问题讨论】:

  • 使用 do-while 循环,如 assylias 下面的回答中所述,并使用 commons apache 的 StringUtils 类来确定输入是否为整数。

标签: java if-statement int


【解决方案1】:

您可以使用a while loop 重新执行该部分代码,直到用户输入正确的整数值。

do {
    input = read user input
} while(input is not an integer)

看来你使用的是Scanner,所以你可以use the hasNextInt method

while (!input.hasNextInt()) {
    let user know that you are unhappy
    input.next(); //consume the non integer entry
}

//once here, you know that you have an int, so read it
int number = input.nextInt();

【讨论】:

  • 在我看来,OP 不知道如何检查输入是否为整数。
  • 对于while部分是否正确:while(input != int)
  • 哇!太感谢了。这对我帮助很大。
【解决方案2】:

这是假设您担心用户在输入时输入的不是整数:

public static void main(String[] args) {
    Integer integer = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer:");
    String line = sc.next();
    integer = tryParse(line);
    while(integer == null){
        System.out.print("The input format was incorrect, enter again:");
        integer = tryParse(sc.next());
    }
    int value = integer.intValue();
}

public static Integer tryParse(String text){
    try{
        return new Integer(text);
    } catch
    (NumberFormatException e){
        return null;
    }
}

【讨论】:

  • 解析入口有什么意义?您已经调用hasNextInt 来确定条目是否为整数...
  • @assylias 哎呀,改成我的意思了。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2020-07-30
相关资源
最近更新 更多