0

In this part of the code, a scanner asks the user to input a number between one and five. I will need to rewrite this for a bunch of variables, so is there any way to make it shorter?

if (Q1 != 1 || Q1 != 2 || Q1 != 3 || Q1 !=4 || Q1 != 5) {
    System.out.println("Error: Please enter a number between 1 and 5.");
}

Instead of typing Q1 != 1 or 2 or 3 etc, is there a way to write 1-5 or something like that?

3 Answers3

6

Try this,

if(Q1 <1 || Q1 >5) System.out.println("Error: Please enter a number between 1 and 5.")
Zeus
  • 2,213
  • 8
  • 28
  • 45
  • I'd be completely satisfied with this answer if you left an explanation as to why it works. I admit it's pretty apparent, but still... – Makoto Apr 09 '16 at 23:25
  • Since you're checking the values over a range instead of discreet random numbers this should work. The If statement checks the input against the range. – Zeus Apr 09 '16 at 23:27
  • It was apparent, I do know why it works. I'm just dumb and didn't even think of it. – Carson Miller Apr 09 '16 at 23:28
-1

For the general case, use a set.

Declare a class field, or a local variable:

Set<Integer> accepted = new LinkedHashSet<>(Arrays.asList(1,2,3,4,5));

Then:

if (!accepted.contains(Q1))
    System.out.println("Error: Please enter a number that is one of: " + accepted);

Use LinkedHashSet so the printed version has the same order as the declaration.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
-1

The above answers are nice for this specific problem, but if you have 5 separate Strings for example, and you want to check if each of them are valid (they aren't null or empty), then you should create a method, to do that.

public boolean isValid(String... args) { 
    for (String s : args) {
        if (s == null or s.equals("")) {
            //Something is invalid 
            return false;
        }
    }
    //Everything is valid
    return true;
}
Bálint
  • 4,009
  • 2
  • 16
  • 27