2

I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.

    System.out.println("Enter a ten digit binary number.  Press 'Enter' after each digit.  Only use one or zero. :");

        binary[0] = keyboard.nextInt();

        for (index = 1; index < 10; index++)
            binary[index] = keyboard.nextInt();// fill array with 10 binary
                                                // digits from user. User
                                                // must press 'Enter' after
                                                // each digit.
0

2 Answers 2

2

Try this:

    Scanner scanner = new Scanner(System.in);
    if (scanner.hasNext())
    {
        final String input = scanner.next();
        try
        {
            int num = Integer.parseInt(input, 2);
        }
        catch (NumberFormatException error)
        {
            System.out.println(input + " is not a binary number.");
            //OR You may exit here, if you don't want to continue
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Please I have to wait for 5 hours to (+1) upvote this, something I learned today with your answer. Nice One :-) Please give me that time, I loved your answer. My limit to upvote is gone for today :-(
+1, I got my voting rights back, hehe, so the first one is coming your way :-)
1

Try this code part :

import java.util.Scanner;

public class InputTest
{
    public static void main(String... args) throws Exception
    {
        Scanner scan = new Scanner(System.in);

        int[] binary = new int[10];
        for (int index = 0; index < 10; index++)
        {
            int number = scan.nextInt();
            if (number == 0 || number == 1)
            {
                binary[index] = number;
                System.out.println("Index : " + index);
            }
            else
                System.exit(0);
        }
    }
}

Comments

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.