验证Java中输入的类型和整数范围

时间:2018-10-16 21:05:58

标签: java validation if-statement while-loop integer

这是我正在为大型项目工作的一小段代码:

import java.util.Scanner;

public static void getZip() {
   boolean shallNPass=true;
   int zip=0;

   System.out.print("Enter zipcode: ");
    while(shallNPass) {
        if(in.hasNextInt()) {
            zip = in.nextInt();
            if(zip>999 && zip<100000)
                zip = in.nextInt();
            else {
                System.out.println("Incorrect length for a zip. Try again");
                System.out.print("Enter zipcode: ");
                continue;
            }
            shallNPass = false;
        }
        else {
            System.out.println("Invalid Entry. Please use an integer.");
            System.out.print("Enter zipcode: ");
            continue;
        }
        shallNPass = false;
    }   shallNPass = true;  //RESETTING SHALLNPASS

    System.out.println(zip);
    //In actuality I continue to do another similar while loop similar after this
    //but I don't want to make this longer, so used a print
}

它基于我在此处找到的关于验证用户输入某种类型值的解决方案。我只是更进一步,尝试验证输入的值在1000和99999之间。

我遇到的问题是,在输入正确长度的整数后,我必须再次输入它才能使程序继续到下一行代码。验证类型时,我没有这个问题,只是在添加长度时。

我该如何解决?我已经尝试过使用continue,break和嵌套循环的各种技巧,但我只是没有看到它。

2 个答案:

答案 0 :(得分:0)

我在这里看到您再次要求它:

if (in.hasNextInt()) {
    zip = in.nextInt(); // asking for input once
    if (zip > 999 && zip < 100000) {
        zip = in.nextInt(); // if validates, you're asking for input again
    } else {
        System.out.println("Incorrect length for a zip. Try again");
        System.out.print("Enter zipcode: ");
        continue;
    }
    shallNPass = false;
}

重构if-else块:

if (zip <= 999 || zip >= 100000) {
    System.out.println("Incorrect length for a zip. Try again");
    System.out.print("Enter zipcode: ");
    continue;
}

如果验证不正确,则只需再次提示;因此,您不需要else

答案 1 :(得分:0)

非常感谢,这是我的固定解决方案。为了摆脱继续,选择保留扩展的嵌套if语句。没有他们,阅读起来会更直接。

System.out.print("Enter zipcode: ");
    while(shallNPass) {
        if(in.hasNextInt()) {
            zip = in.nextInt();
            if(zip>999 && zip<100000) 
                shallNPass=false;
            else {
                System.out.println("Invalid Entry. Wrong length for a zip.");
                System.out.print("Enter zipcode: ");
            }
        }
        else {
            System.out.println("Invalid Entry. Please use an integer.");
            System.out.print("Enter zipcode: ");
            in.next();
        }
    }   shallNPass = true;  //RESETTING SHALLNPASS