0

I have this piece of code to validate an input, this input is relative to a bet made by an user

  • it needs to be an int
  • it needs to be greater than 0
  • it needs to be lower than the credits available (the user credits)
  1. if the user writes a string it should say: input + " is not a valid number"
  2. if the user writes an int below or equals to zero it should continuously saying: "Please enter a positive number: "
  3. if the user writes an int higher than the credits available it should say: "not enough credits"

the code I have right now is the following:

Scanner scanner = new Scanner(System.in);
int number;
do {
    System.out.print("Please enter a positive number: ");
    while (!scanner.hasNextInt()) {
        String input = scanner.next();
        System.out.printf(input + " is not a valid number.\n");
    }
    number = scanner.nextInt();
} while (number < 0);

System.out.printf("You have entered the number " + number);

I have the 1. and 2. figure it out with this code, but I can't for nothing add the third (3.) statement as it asks for double the same input or it gives an error InputMismatchException because it suppose to be an integer, but on test sometimes does that.

the number is suppose to be the bet

Please help xD

1 Answer 1

1

You logic is rather convoluted and hard to follow. I think after this assignment you should ask for some help and find a better way to structure this code. (For now, instructors usually require you to turn in your own work so I'm not going to try to change your code.)

The way you have the code now you'll have to do the final check in two parts. First, check and then decide whether to print the error message. Second, check and decide whether to continue the loop.

do {
    System.out.print("Please enter a positive number: ");
    while (!scanner.hasNextInt()) {
        String input = scanner.next();
        System.out.printf(input + " is not a valid number.\n");
    }
    number = scanner.nextInt();
    if( number > credits )
        System.out.println( "Not enough credits." );
} while (number < 0 || number > credits);
Sign up to request clarification or add additional context in comments.

1 Comment

I am not necessary attached to this code, if you come with a better, efficient and overall more practical way than this one to get an input that is an int between 1 and other int, be my guest xD

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.