I am writing a simple program to get user input from Scanner to perform some tasks,
I want to get user input only from the number 1 to 3,
any negative number or string will display an error message and prompt user to re-enter.

Here's comes the problem...

When I enter String, it display proper error message -> "Invalid, enter again : "

However, when I enter any number less than 0 or more than 3,
it display the error message of -> "Enter option: "

Another problem, let say if I enter negative number, e.g. -123
then when I enter String, the error message "Invalid, enter again : " will immediately show twice...

My coding...

import java.util.Scanner;

public class Main {

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

        do {
            System.out.print("Enter option: ");
            while (!scan.hasNextByte()) {
                System.out.print("Invalid, enter again : ");
            option = scan.nextByte();
        } while (option < 0 || option > 3);

        switch (option) {
            case 1:
            case 2:
            case 3:

Need help to solve the problem, which all the error message is display "Invalid, enter again : "

You are confusing bytes that represent characters, eg '1'. '2' and bytes that contain a binary number eg 1, 2
Your option = scan.nextByte() will give you the ASCII code for '1' (etc), which is a numeric value of about 49 if I remember correctly.

Hi JamesCherrill, it doesn't matter is byte or int datatype in this case.
When I declare the option as int, the error message still appears as same as I described... =)

OKay JamesCherrill I've changed to int.
But still, the same error cames out... =(

Why do you keep going on about ints? I never said anything about ints. You can't fix this by changing to int. Please re-read what I posted.

This article has been dead for over six months. Start a new discussion instead.