英文:
"I will guess your age" game not working properly
问题
import java.util.Scanner;
public class kouzlo {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int currentyear = 2020;
System.out.println ("欢迎!我可以猜出你的年龄。你是哪一年出生的?");
int yearofbirth = scanner.nextInt();
System.out.println ("你今年过生日了吗?");
boolean yes, Yes, YES, y, Y = true;
boolean no, No, NO, n, N = false;
boolean hadbirthday = scanner.hasNextBoolean();
int summary = currentyear - yearofbirth;
int summary2 = currentyear - yearofbirth - 1;
if (hadbirthday == true) {
System.out.println("你今年 " + summary + " 岁!");
}
else {
System.out.println("你今年 " + summary2 + " 岁!");
}
}
}
英文:
I tried to make a really simple "I will guess your age" game. When I say that I haven't had birthday this year, it works just fine, but when I say that I had birthday this year, it does the same thing as when I say I didn't. For example, when i say that i was born in 2000 and say that i haven't had birthday this year, it would say that I'm 19 years old, which is correct. But when I say that I had birhday this year, it also says that I'm 19, which is, obviosly, not correct. Can someone please tell me where is the problem? Any help would be appreciated, thanks. ![]()
import java.util.Scanner;
public class kouzlo {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int currentyear = 2020;
System.out.println ("Welcome! I can guess your age. What year were you born?");
int yearofbirth = scanner.nextInt();
System.out.println ("Have you had your birthday this year?");
boolean yes, Yes, YES, y, Y = true;
boolean no, No, NO, n, N = false;
boolean hadbirthday = scanner.hasNextBoolean();
int summary = currentyear - yearofbirth;
int summary2 = currentyear - yearofbirth - 1;
if (hadbirthday == true) {
System.out.println("You're " + summary + " years old!");
}
else {
System.out.println("You're " + summary2 + " years old!");
}
}
}
答案1
得分: 1
为了回答你的问题,Federico的评论是正确的。你需要像这样做:
boolean hadbirthday = false;
if (scanner.hasNextBoolean()) {
hadbirthday = scanner.nextBoolean();
};
我还注意到了这些代码行:
boolean yes, Yes, YES, y, Y = true;
boolean no, No, NO, n, N = false;
看起来这些是没有用的。如果你想允许用户输入其中之一,并将其解释为布尔值,你需要使用hasNext() / next(),然后检查生成的字符串是否与你的模式之一匹配。
英文:
To answer your question, the comment of Federico is right. You need to do something like:
boolean hadbirthday = false;
if (scanner.hasNextBoolean()) {
boolean hadbirthday = scanner.nextBoolean();
};
I also see these lines:
boolean yes, Yes, YES, y, Y = true;
boolean no, No, NO, n, N = false;
which seems to be useless. If you want to allow the user to enter one of those and interpret it as a boolean, you will have to use hasNext() / next() and check if the resulting string matches one of your patterns.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论