I'm making a rock paper scissors game for school and I have a working game but its 213 lines long. I was trying to shorten it up some by adding switch case in place of my if statements. Are there some instances where a switch case just won't work and it has to be an if statement?
String weaponChoice = keyboard.nextLine();
switch(weaponChoice) {
case "Rock":
System.out.println("You Chose Rock"); break;
case "Paper":
System.out.println("You Chose Paper"); break;
case "Scissors":
System.out.println("You chose Scissors"); break;
default:
System.out.println(weaponChoice + " is not a valid answer the computer gets a point!");
compScore++;
break;
}
I had the above code in an if statement and switched it over no problem but the below code I'm not sure how to change it over.
String getComputerChoiceVariable = getComputerChoice();
System.out.println("The computer chose " + getComputerChoiceVariable);
if(weaponChoice.equals(getComputerChoiceVariable)) {
System.out.println("It's a draw!");
ties++;
} else if((weaponChoice.equals("Rock")) && (getComputerChoiceVariable.equals("Scissors"))) {
System.out.println("You won!");
userScore++;
} else if((weaponChoice.equals("Paper")) && (getComputerChoiceVariable.equals("Rock"))){
System.out.println("You won!");
userScore++;
} else if((weaponChoice.equals("Scissors")) && (getComputerChoiceVariable.equals("Paper"))){
System.out.println("You won!");
userScore++;
} else if(weaponChoice.equals("Rock") && getComputerChoiceVariable.equals("Paper")) {
System.out.println("You Lost!");
compScore++;
} else if(weaponChoice.equals("Paper") && getComputerChoiceVariable.equals("Scissors")) {
System.out.println("You Lost!");
compScore++;
} else if(weaponChoice.equals("Scissors") && getComputerChoiceVariable.equals("Rock")) {
System.out.println("You Lost!");
compScore++;
}
Maybe something like
switch(weaponChoice, getComputerChoiceVariable){
case "Rock", case "Scissors":
System.out.println("You won!");
}
But Java doesn't like that I get a ton of errors. Can a switch take two parameters? I'm super new to Java. Could I somehow use the && to compare cases?
Aucun commentaire:
Enregistrer un commentaire