so I am making a simple program for a school project. I am running into a problem where when I run it and it goes to the if statement where you rerun the program if you get it wrong, and it does not rerun it. No matter what I select (yes or no) it just goes to the else statement. I cant seem to see what is wrong. Thanks for any help!
package com.nathandevelops;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int correctNumber = (int) (Math.random() * 100 1);
System.out.println(correctNumber);
System.out.print("Guess the right number: ");
int guess = scanner.nextInt();
if (guess == correctNumber) {
System.out.println("Correct!");
} else if(guess != correctNumber){
System.out.print("That was incorrect! The correct answer is " correctNumber ". Would you like to play again? (yes/no)");
String tryAgain = scanner.next();
if (tryAgain == "yes") {
// main(new String[]{});
System.out.println("ok");
} else if (tryAgain == "no"){
System.out.println("Ok! Goodbye!");
System.out.println(tryAgain);
} else {
System.out.println("OK!");
System.out.println(tryAgain);
}
}
}
}
CodePudding user response:
Try using tryAgain.equals()
instead of ==
. In Java, strings are compared with the .equals()
method, not with the equality operator.