0

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 !

P.Mach
  • 3
  • 1
  • 3

4 Answers4

1

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.")
}
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
0

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.")
}
Mykola Yashchenko
  • 5,103
  • 3
  • 39
  • 48
0

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.

user1983983
  • 4,793
  • 2
  • 15
  • 24
0

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

Quirinux
  • 310
  • 2
  • 7