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!");
}
}
}
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.