Also ich bin wirklich neu in Java und ich versuchte zu üben, während und wenn Aussagen durch eine Ratespiel App.Ratespiel, (While-Schleife, if-Anweisung), wieder spielen prompt nicht funktioniert
Alles schien zu funktionieren, bis ich aufgefordert werde, wieder zu spielen. Wenn ich Y eintippe, endet die Schleife. Dies soll nicht passieren, da das Argument while am Anfang des Codes sagt, dass man "keepPlaying" wenn es wahr ist.
Ich habe versucht, mit dem Argument zu spielen, um es zu machen: while (antwort == "Y"). Ich habe damit herumgespielt, aber es bleibt immer spannend. Bitte helfen Sie !!
Hier ist der Code:
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
// TODO Auto-generated method stub
String answer = "Y";
int guess;
int number;
String again;
boolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepPlaying)
{
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = sc.nextInt();
while (guess > 10 || guess < 1)
{
System.out.print("I said, between 1 and 10. Try again: ");
guess = sc.nextInt();
}
number = (int)(Math.random() *10 + 1);
if (guess == number)
{
System.out.println("You're right!");
}
else
{
System.out.println("You're wrong! the number was " + number);
}
System.out.print("Play again? (Y or N)");
answer = sc.next();
if (answer == "Y")
{
keepPlaying = true;
}
else
{
break;
}
}
System.out.println("Thank you for playing");
}
}
Strings werden nicht verglichen mit '==' aber '.equals()' – KevinO