This question already has an answer here:
- How do I compare strings in Java? 23 answers
I've been trying to create a game from scratch for my beginners level Java class I am taking at my school. While programming the game I ran into some problems with my if/else statements. From my troubleshooting, I have found that all of the code runs up until the point where it reaches the if/else statement and then it stops, there are no error messages, it just stops as if it was done running. The desired result of the code is to have the player either attack or run away but for purposes of this question, I removed the run away option in the code. Here is the portion of my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gold = 0;
System.out.print("While trudging through the murky water you stumble upon an alligator. You may choose to attack or run away, please make your decision: ");
String sAction = input.nextLine();
if (sAction == "attack") {
int sChanceOfAttack = (int)(Math.random() * 4 + 1);
int sChanceOfBeastDodge = (int)(Math.random() * 12 + 1);
if (sChanceOfAttack == sChanceOfBeastDodge) {
System.out.print("The alligator dodged your attack and ran away, you receive nothing.");
} else {
System.out.print("You slayed the beast: +100 gold and fully healed");
gold += 100;
}
}
At one point I attempted to modify the if/else statement like this:
if (sAction == "attack") {
int sChanceOfAttack = (int)(Math.random() * 4 + 1);
int sChanceOfBeastDodge = (int)(Math.random() * 12 + 1);
if (sChanceOfAttack == sChanceOfBeastDodge) {
System.out.print("The alligator dodged your attack and ran away, you receive nothing.");
} else if (sChanceOfAttack != sChancOFBeastDodge) {
System.out.print("You slayed the beast: +100 gold and fully healed");
gold += 100;
}
}
However, that did not do anything to solve the problem. Thank you for all the help you can give.
Aucun commentaire:
Enregistrer un commentaire