0

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

}

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

To get appropriate month name, you need to use month number as index into monthName to get month actual name: System.out.println("The month is: " + monthName[monthNumber]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.