尝试制作我的代码,以便我可以询问用户是否想再次播放,但是我很困惑我应该如何解决这个问题。
Scanner in = new Scanner(System.in);
int randomNum = 1 + (int)(Math.random() * 100);
System.out.println(randomNum);
Boolean playAgain = true;
while (playAgain) {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int guessNum = in.nextInt();
while ((guessNum > randomNum) || (guessNum < randomNum)) {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}
System.out.println("You got it!\nPlay again? (Y/N) ");
String answer = in.next();
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
}
答案 0 :(得分:1)
您使用了==
等于关系运算符,它通常用于检查字符串引用而不是实际值。因此,即使答案包含y
,您的条件表达式也不会将true
作为结果返回。
供参考:Visit Here For More Info ( '==' vs 'equals()' method)
String answer = in.next();
//problem with this line becuase == operator use to check reference instead of value
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
所以改变你的代码如下所示
String answer = in.next();
if (answer.startsWith("y") || answer.startsWith("Y")) { // Now this willl work fine to your code
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
答案 1 :(得分:0)
如果您想使用playAgain var,请使用
from keras.applications.resnet50 import ResNet50
import keras.layers
# this could also be the output a different Keras model or layer
input = keras.layers.Input(shape=(400, 400, 1)) # this assumes K.image_dim_ordering() == 'tf'
x1 = keras.layers.AveragePooling2D(pool_size=(2,2))(input)
x2 = keras.layers.Flatten()(x1)
x3 = keras.layers.RepeatVector(3)(x2)
x4 = keras.layers.Reshape((200, 200, 3))(x3)
x5 = keras.layers.ZeroPadding2D(padding=(12,12))(x4)
m = keras.models.Model(input, x5)
model = ResNet50(input_tensor=m.output, weights='imagenet', include_top=False)
比较两个字符串而不是answer.equals("y")
。
否则在阻止或执行时将完整代码放在内部。如果用户想要玩,那么继续,否则休息;
==
答案 2 :(得分:0)
它可以帮助你
do {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int randomNum = 1 + (int) (Math.random() * 100);
System.out.println(randomNum);
int guessNum = in.nextInt();
do {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}while ((guessNum > randomNum) || (guessNum < randomNum));
System.out.println("You got it!\nPlay again? (Y/N) ");
answer = in.next();
}while(answer.equals("y"));