简体   繁体   中英

User input validation using While loop

I am having trouble with this Java program validating user input using a while loop. I must use a while loop. The program works fine until the user enters a number that isn't valid which is when it prints Invalid number entered infinitely. Beginner level sorry, but Thank you for the help!

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]);
    }
}

EDIT After switching the while loop of the code to this: It still does not give the month name

    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);
}

}

Because after you read the number, you start the loop based on value read, but never change the variable, so if while condition is true, it will be true forever. Add another call to nextInt(), like the following:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM