vendredi 18 décembre 2020

Is there a simpler way to write this chain of equalsIgnoreCase checks?

I am attempting to write a method that takes user input in the form of a string, and then returns an int value based on what the string contained/equals. I have already wrote a method that works, but it is quite long, and I was wondering if there was a way to make it shorter?

This is the method in its current state:

private int readCommandInput(){
    System.out.print("Command?>");
    String userCommand = programAssignment.assignmentScanner.nextLine();
    if(userCommand.equalsIgnoreCase(registerNewDogCMD)){ return 1; }
    else if(userCommand.equalsIgnoreCase(listDogsCMD)){ return 2; }
    else if(userCommand.equalsIgnoreCase(increaseDogAgeCMD)){ return 3; }
    else if(userCommand.equalsIgnoreCase(removeDogCMD)){ return 4; }
    else if(userCommand.equalsIgnoreCase(registerNewOwnerCMD)){ return 5; }
    else if(userCommand.equalsIgnoreCase(giveDogCMD)){ return 6; }
    else if(userCommand.equalsIgnoreCase(listOwnersCMD)){ return 7; }
    else if(userCommand.equalsIgnoreCase(removeOwnerCMD)){ return 8; }
    else if(userCommand.equalsIgnoreCase(startAuctionCMD)){ return 9; }
    else if(userCommand.equalsIgnoreCase(makeBidCMD)){ return 10; }
    else if(userCommand.equalsIgnoreCase(listBidsCMD)){ return 11; }
    else if(userCommand.equalsIgnoreCase(listAuctionsCMD)){ return 12; }
    else if(userCommand.equalsIgnoreCase(closeAuctionsCMD)){ return 13; }
    return 0;
}

Some extra information:

  • The variables that with the prefix CMD are all strings that are defined earlier in the program, as well as what the user will need to put in to execute the various commands. For example, makeBidCMD is defined as "Make Bid".
  • The method has to be able to take all of these 13 different commands from the user, as well as return a 0 if the user inputs an incorrect command. So in total, it has to be able to return 14 different values.
  • The method has to take the input in string format. I can't make the user write a number for the command they want to execute and take the input as an int, for example.

Aucun commentaire:

Enregistrer un commentaire