Carson Miller
Carson Miller

Reputation: 31

Is there a way to shorten something like this?

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?

Upvotes: 0

Views: 72

Answers (3)

Bálint
Bálint

Reputation: 4039

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;
}

Upvotes: -1

Bohemian
Bohemian

Reputation: 424983

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.

Upvotes: -1

Zeus
Zeus

Reputation: 2253

Try this,

if(Q1 <1 || Q1 >5) System.out.println("Error: Please enter a number between 1 and 5.")

Upvotes: 6

Related Questions