cdm89
cdm89

Reputation: 51

What is the proper way to prevent a program from exiting after a user enters wrong input in Java?

The Task

Design and implement an application that reads an integer value and prints out the sum of all EVEN integers between 2 and its input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.

Note: the lesson was on while loops, not other loops such as for loop etc

The Issue

I have everything working, however something about how I have written this feels wrong. I currently have a while loop while(programOn) to keep the program running. without this while loop, if the user enters a number < 2, the user is asked to try again, however if the user tries again, the program exits instead of running the new input into the program. So, I created the while loop to force the program open until the user types an acceptable input.

- something about this feels hacky and incorrect i would really appreciate some validation on my method.

public static void main(String[] args){
int inputNumber;
int sum = 0;

boolean programOn = true;

Scanner scan = new Scanner(System.in);

System.out.println("Please Type a number no smaller than 2");
inputNumber = scan.nextInt();

//include the original input to sum
sum = inputNumber;

while(programOn){
    if(inputNumber < 2){
      System.out.println("you need a number greater than or equal to 2, try again");

      inputNumber = scan.nextInt();
      sum = inputNumber;

    }else{

    //from the number chosen divide until you reach 0

    while(inputNumber != 0){

      //subtract one from the number
      inputNumber = (inputNumber - 1);

      if((inputNumber % 2 == 0) && (inputNumber != 0)){
        System.out.println(inputNumber);
        //add the input to the sum
        sum += inputNumber;
      }
    }
      System.out.println("The sum is " + sum);
      programOn = false;
  }
}


}

Upvotes: 0

Views: 822

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30819

That's because the validation is done by an if condition. What you need here is a while loop that keeps asking for inputs as long as user's input is less than 2, below is the code snippet that does this:

Scanner scan = new Scanner(System.in);

System.out.println("Please Type a number no smaller than 2");
int inputNumber = scan.nextInt();

while(inputNumber < 2){
    System.out.println("you need a number greater than or equal to 2, try again");
    inputNumber = scan.nextInt();
}

System.out.println(inputNumber);

Upvotes: 3

Related Questions