P.Mach
P.Mach

Reputation: 3

Multiple variables in If statement?

I'm fairly new to Java language and I'm having bit of problem.

I'm trying to make really simple Battle ships game. I have an array 3x3 filled with 0 and 1. 1 meaning there is a boat.

Every slot in the array is named n-n8. And I was wondering if there was a way of naming all the variables in one if statement.

The way I'm doing it right now is

if((n == 1 && x.equals("n") || (n == 1 && x.equals("n1") .. (n == 1 && x.equals("n8")){
System.out.println("Nice shot. Boat down.")}

x is user input. You probably get the point. So I would like to know if there's a way to shorten down the if statement or there's no other way. Something like :

if(n, n1, n2.. n8)

I tried looking it up but no success. Thank you in advance !

Upvotes: 0

Views: 7711

Answers (4)

Quirinux
Quirinux

Reputation: 326

Mykola went right to the point, I'd suggest another option as seen here:

if(n == 1 && Arrays.asList(yourArray).contains(['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8']);){
    System.out.println("Nice shot. Boat down.")
}

I don't have a jdk installed now to check it properly, but this is the ideia

Upvotes: 0

DodgyCodeException
DodgyCodeException

Reputation: 6123

A couple of alternatives:

Using a regular expression (works with Java 7/8/9):

if (n == 1 && x.matches("n[1-8]?") {
    System.out.println("Nice shot. Boat down.")
}

Using the new Java 9 List.of convenience method (alternative to Arrays.asList):

if (n == 1 && List.of("n", "n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8").contains(x) {
    System.out.println("Nice shot. Boat down.")
}

Upvotes: 1

user1983983
user1983983

Reputation: 4841

You can create a list of the eight names and use contains

if (n == 1 && Arrays.asList("n", "n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8").contains(x)) {
    System.out.println("Nice shot. Boat down.")
}

This approach also happens to be null-safe.

Upvotes: 0

Mykola Yashchenko
Mykola Yashchenko

Reputation: 5371

Java has no similar operators to those you mention. But you can rewrite your code using for loop:

for (String number : Arrays.asList("n", "n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8")) {
    if (n == 1 && x.equals(number)) {
        System.out.println("Nice shot. Boat down.");
        break;
    }
}

Or even better to use contains instead of loop

List<String> numbers = Arrays.asList("n", "n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8");
if (n == 1 && numbers.contains(x)) {
    System.out.println("Nice shot. Boat down.")
}

Upvotes: 0

Related Questions