使用While循环进行用户输入验证

时间:2015-12-04 00:27:46

标签: java arrays string input while-loop

我在使用while循环验证用户输入的Java程序时遇到问题。我必须使用while循环。该程序正常工作,直到用户输入无效的数字,即无效打印无效数字。初级水平抱歉,但感谢您的帮助!

public class monthName {    
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
                "October", "November", "December" };

        // monthName[0]="January";
        // monthName[1]="February";
        // monthName[2]="March";
        // monthName[3]="April";
        // monthName[4]="May";
        // monthName[5]="June";
        // monthName[6]="July";
        // monthName[7]="August";
        // monthName[8]="September";
        // monthName[9]="October";
        // monthName[10]="November";
        // monthName[11]="December";

        int monthNumber = 0;
        System.out.println("Enter a month number: ");
            monthNumber = console.nextInt();
        while (monthNumber > monthName.length || monthNumber < 1) {
            System.out.println("Invalid number entered");
        }   
        System.out.println("The Month is: " + monthName[monthNumber - 1]);
    }
}

修改 将代码的while循环切换为: 它仍然没有给出月份名称

    int monthNumber = 0;
    System.out.println("Enter a month number: ");
    monthNumber = console.nextInt();
    while (monthNumber > monthName.length || monthNumber < 1) {
        System.out.println("Invalid number entered");
        System.out.println("Enter a month number: ");
        monthNumber = console.nextInt();
    }
    System.out.println("The month is: " + monthName);
}

}

1 个答案:

答案 0 :(得分:1)

因为在读完数字之后,你会根据读取的值开始循环,但永远不会改变变量,所以如果条件为真,它将永远为真。添加对nextInt()的另一个调用,如下所示:

int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
    System.out.println("Invalid number entered");
    System.out.println("Enter a month number: ");
    monthNumber = console.nextInt();
}