1

I'm currently making a program and I want to take a input of either "Red" or "Black" and then a number from 1-10. Input should look like Red 7 or Black 3

I want the program to reprint the line if the input is invalid. I was thinking about using a try { and then catch {. But I'm unsure what condition to check.

I tried this:

    System.out.print("Please choose Black or Red....and a number from 1-10 (Example : Black 4): ");
        String color = input.next();
        int number = input.nextInt();
    if(!color.equals("Red") || !color.equals("red") || !color.equals("Black") || !color.equals("black")) {
        System.out.println("Incorrect input. Please enter Black or Red: ");
        color = input.next();
    }
    if(!(number < 0 || number > 10)) {
        System.out.println("Incorrect input. Please re-enter a valid number from 1 to 10: ");
        color = input.next();
   }
PizzaParrot
  • 121
  • 6

3 Answers3

2

There are quite a few approaches to this situation. I suggest the following, which reads input by line:

  1. Separate the input into an array using String#split(regex).
  2. Check the color input using String#equalsIgnoreCase(String).
  3. Parse the number input using Integer#parseInt(String).
  4. Check the number input using a switch.

When all thrown together, it will look something like this:

System.out.println("Please choose Black or Red....and a number from 1-10: ");
Scanner input = new Scanner(System.in);

boolean flag = true;
while (flag) {
    String line = input.nextLine();
    String[] parts = line.trim().split("[\\s]");

    try {
        int num = Integer.parseInt(parts[1]);

        if (parts[0].equalsIgnoreCase("red")) {
            switch (num) {
                case 1:
                    {
                        flag = false;
                        //...
                    }
                    /*
                     * I'm not going to include all the cases
                     */

                default:
                    throw new NumberFormatException();
            }
        } else if (parts[0].equalsIgnoreCase("black")) {
            switch (num) {
                case 1:
                    {
                        flag = false;
                        //...
                    }
                    /*
                     * I'm not going to include all the cases
                     */

                default:
                    throw new NumberFormatException();
            }
        } else {
            System.out.println("'" + parts[0] + "' is invalid." 
                + "\nPlease re-enter a color");
        }
    } catch (NumberFormatException e) {
        System.out.println("'" + parts[1] + "' is invalid."
            + "\nPlease re-enter a number");
    }

}

There is, of course, a cleaner approach which uses methods and things, but for the sake of a clean answer I am not going to include that.

Cardinal System
  • 2,227
  • 2
  • 18
  • 33
1

ALong with what @hoobit said, also for checking a condition use the .equalsIgnoresCase method

So:

 Scanner input = new Scanner(System.in);

    String color = "";
    int number = -1;
    while(!color.equalsIgnoreCase("Black") || !color.equalsIgnoreCase("Red") && (number < 0 || number > 10))
    {  
        System.out.print("Please choose Black or Red....and a number from 1-10: ");
        color = input.next();
        number = input.nextInt();
    }
    // \n puts that "quote" on the next line
    System.out.println("Color chose: " + color + "\nnumber chose: " + number);

As requested by OP:

So just make sure to import the exception to be caught that crashed the program before, so before if they entered 2 strings, instead of a String and a int, it would crash, now it wont. It will now CATCH the "Crash" and keep going.

import java.util.InputMismatchException;

Now for the code:

 Scanner input = new Scanner(System.in);


    String color = "";
    int number = -1;


        while(!color.equalsIgnoreCase("Black") || !color.equalsIgnoreCase("Red") && (number <= 0 || number >= 10))
        {  
                try
                {
                    System.out.print("Please choose Black or Red....and a number from 1-10: ");
                    color = input.next();
                    number = input.nextInt();
                }
                catch(InputMismatchException e) //More specific error
                {
                    e.getMessage(); 
                    System.out.println("Invalid entry, most specific. ");

                }
                catch(Exception e) //less specific general error
                {
                    e.getMessage();
                    System.out.println("unknown entry error.");
                }

        }

         // \n puts that "quote" on the next line
        System.out.println("Color chose: " + color + "\nnumber chose: " + number);
EOxJ
  • 102
  • 7
  • But what if they enter lets say "9 Red", which is not valid input, how, can i make it so that it detects that. – PizzaParrot Apr 22 '18 at 23:13
  • What do you mean? detect that they entered a int first and String the next ? It will automatically take the "9", because its a string being taken in. But the next input, the "Red" there will be a run time error, because its expecting int and not a string? – EOxJ Apr 22 '18 at 23:18
  • Like what if they entered "Red Red" it just gives me an error and ends the program. – PizzaParrot Apr 22 '18 at 23:23
  • Yes it will, do you want it to "catch" that error and keep prompting the user to keep going until they enter the correct information? – EOxJ Apr 22 '18 at 23:26
  • Yes, I'd also like it to do that. I'd really appreciate if you could show how to do that aswell. – PizzaParrot Apr 22 '18 at 23:28
  • 1
    Okay, I added it to my original post :) – EOxJ Apr 22 '18 at 23:33
  • Sorry, for all the edits, im finished now – EOxJ Apr 22 '18 at 23:43
  • good, and no problem. – EOxJ Apr 22 '18 at 23:48
0

You will put this in a while loop because you want to keep printing it until the user puts in a valid input. The while loop condition is if the the color doesn't equal red or black, and the number is not between 1-10 (the input is invalid). So if the input is invalid, it will keep asking for different colors and numbers, and if the input is valid, it will go out of the while loop.

String color = "";
int number = -1;

while(!color.equals("Black") || !color.equals("Red") && (number < 0 || number > 10){  
    System.out.print("Please choose Black or Red....and a number from 1-10: ");
    color = input.next();
    number = input.nextInt();
}
hoobit
  • 36
  • 2