Home > OS >  Asking for user input until value between -5 and 5 is entered in java
Asking for user input until value between -5 and 5 is entered in java

Time:06-12

I'm trying to creating some code which asks for user input until the value being entered is between -5 and 5 but am having some trouble with it, currently it works the first time an invalid input is entered but if a second invalid input is entered then the program accepts that value, my current code is:

            int choice;
            Scanner sc = new Scanner(System.in);
            choice = sc.nextInt();
            if(choice<=-5 || choice>=5)
            {
                    System.out.println("==================================" "\n" "INVALID INPUT! PLEASE TRY AGAIN: " "\n" "==================================");                               
                    choice = sc.nextInt();
            }
            else
            {
                    // do stuff
            }

CodePudding user response:

The code you've posted has no notion of doing something "until" some condition is met - you're only reading the input once and then making a decision based on that. You need to go and learn about loops for repeating things.

CodePudding user response:

First, you need to start with an infinite loop like while that runs until a number between -5 and 5 is entered then you do break

And since you want to read the user's input then you need to specify a condition for the while loop like while(input.hasNext()).

Also, reading inputs with hasNext() returns a String so you need to change it to int with parseInt(n)

import static java.lang.Integer.parseInt;
import java.util.Scanner;

public class Mavenproject1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while (input.hasNext()) {
            String n = input.next();
            int number = parseInt(n);
            if (number >= -5 && number <= 5) {
                System.out.println("==================================" "\n" "INVALID INPUT! PLEASE TRY AGAIN: " "\n" "==================================");   
                break;
            }
//            System.out.println(n);
            
        }
        input.close();
    }
}

You can as well use hasNextInt() & nextInt() if you are sure inputs are always integers value so you don’t need to parse the string into int:

import java.util.Scanner;

public class Mavenproject1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while (input.hasNextInt()) {
            int n = input.nextInt();
            if (n >= -5 && n <= 5) {
                System.out.println("==================================" "\n" "INVALID INPUT! PLEASE TRY AGAIN: " "\n" "==================================");   
                break;
            }
//            System.out.println(n);
            
        }
        input.close();
    }
}
  •  Tags:  
  • java
  • Related