Home > Back-end >  How to simplify if statements when comparing multiple strings
How to simplify if statements when comparing multiple strings

Time:08-16

Is there a way I can make this code shorter?

Scanner scan = new Scanner(System.in);
String reply = scan.nextLine();

if (reply.equals("rock") || reply.equals("paper") || reply.equals("scissors")){
    /**/
}

CodePudding user response:

    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    String[] as = s.split("\\s");
    String opt = "rock paper scissors" ;
    for(String sl:as){
        if(opt.contains(sl)){
        //blah..blah....
        System.out.println("True");
        }
    }

CodePudding user response:

It would be easiest to go with such code:

Set.of("rock", "paper", "scissors").contains(reply)

The Set could also be stored as an instance field in the class, where it could be parameterized during object creation if needed or as a constant (static final) field with a meaningful name such as (for example) CORRECT_GAME_INPUTS and thanks to that the whole if would look like this:

if (CORRECT_GAME_INPUTS.contains(reply)) {
    // do stuff
}

CodePudding user response:

My preferred way of comparing a list which you cannot add or remove in the program shall be this way, as well as to cater for the OR operand in a single line:

List<String> conditions = Arrays.asList("rock","paper","scissors");
Scanner scan = new Scanner(System.in);
String reply = scan.nextLine();

if (conditions.contains(reply)){
    /**/ 
}

This way it is cleaner and more maintainable in the long run

CodePudding user response:

I would create a string with all the options. Then check to see if the reply is in the string.

      String reply = scan.nextLine();
      String options = "rock paper scissors";
      if (options.contains(reply)){ }
  •  Tags:  
  • java
  • Related