Justin Frisch February 2016

How do I let the user input the variable again after doing an error?

import java.util.Scanner;

public class LeapYear {

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter a year on the Gregorian calendar. (After 1583)");


        int yearEntered = scan.nextInt();

        if (yearEntered < 1583){

            System.out.println("Please enter an integer greater than 1582");
            System.out.println("Try again");

        }else{

                int yearEntered = scan.nextInt();
//this is where I'm messing up

Answers


Muhatashim February 2016

Before I show you can make the user enter the variable again, I want to point out that you are declaring yearEntered again in the else, which is illegal in Java. Simply removing the int there will fix that.

Now, if you had an error from the user entering the wrong input (i.e. 2015 instead of 1580), you can do this:

Scanner scan = new Scanner(System.in);

System.out.println("Please enter a year on the Gregorian calendar. (After 1583)");


int yearEntered = 0; //initialize the variable with a default number
while (scan.hasNext()) { //keep scanning for the user input
    yearEntered = scan.nextInt(); //scan for the next int assuming the user only enters ints

    if (yearEntered < 1583) { //if the user entered less than 1583, then do another iteration till the user finally enters a number greater than or equal to 1582

        System.out.println("Please enter an integer greater than 1582");
        System.out.println("Try again");

    } else {
        break; //exits the loop
    }
}

//code for what you want to do with the correct yearEntered

Post Status

Asked in February 2016
Viewed 2,651 times
Voted 9
Answered 1 times

Search




Leave an answer