gpt4 book ai didi

java - 为什么我的代码退出并且不接受扫描仪拉入的 "yes"或硬编码的代码?

转载 作者:行者123 更新时间:2023-12-02 02:50:02 25 4
gpt4 key购买 nike

看起来扫描仪在这里被正确使用并被正确分配给一个变量,但我无法弄清楚发生了什么。当我在代码中玩这个游戏时,INT 被很好地拉入。由于某种原因,字符串不会被拉入,即使我为字符串硬编码“yes”,它仍然会退出代码。

package testTraining;

import java.util.Scanner;

public class GuessingGame {

static int gamesPlayed; // The number of games played.
static int gamesWon; // The number of games won.

public static void main(String[] args) {
gamesPlayed = 0;
gamesWon = 0; // This is actually redundant, since 0 is
// the default initial value.
System.out.println("Let's play a game. I'll pick a number between");
System.out.println("1 and 100, and you try to guess it.");
String yesno = "yes";
Scanner yesScan = new Scanner(System.in);
do {
playGame(); // call subroutine to play one game
System.out.print("Would you like to play again? ");
yesno = yesScan.next();
} while (yesno == "yes");
System.out.println();
System.out.println("You played " + gamesPlayed + " games,");
System.out.println("and you won " + gamesWon + " of those games.");
System.out.println("Thanks for playing. Goodbye.");
} // end of main()

static void playGame() {
Scanner guessScan = new Scanner(System.in);
int computersNumber; // A random number picked by the computer.
int usersGuess; // A number entered by user as a guess.
int guessCount; // Number of guesses the user has made.
gamesPlayed++; // Count this game.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a randomly
// chosen integer between 1 and 100, inclusive.
guessCount = 0;
System.out.println();
System.out.print("What is your first guess? ");
while (true) {
usersGuess = guessScan.nextInt(); // Get the user's guess.
guessCount++;
if (usersGuess == computersNumber) {
System.out.println("You got it in " + guessCount
+ " guesses! My number was " + computersNumber);
gamesWon++; // Count this win.
break; // The game is over; the user has won.
}
if (guessCount == 6) {
System.out.println("You didn't get the number in 6 guesses.");
System.out.println("You lose. My number was " + computersNumber);
break; // The game is over; the user has lost.
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
System.out.print("That's too low. Try again: ");
else if (usersGuess > computersNumber)
System.out.print("That's too high. Try again: ");
}
System.out.println();
} // end of playGame()

} // end of class GuessingGame

最佳答案

您需要使用 .equals("yes") 而不是 == "yes"来比较字符串

关于java - 为什么我的代码退出并且不接受扫描仪拉入的 "yes"或硬编码的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com