Let's just focus on these lines:
String answer;
...
answer = scan.next();
if (answer == 'y' || answer == 'Y') {
You will notice that I have tweaked the the style to make it more readable and consist with common Java style rules.
You will notice that I have fixed a compilation error by changing Next()
to next()
.
But now for the interesting part:
answer == 'y' || answer == 'Y'
What you are trying to do here is test if the user is trying to reply in the affirmative or the negative; i.e. a response to your `"(Y/N)" question.
There are both technical and logical problems in the way you are doing it. The technical problem is that answer == 'y'
tries to compare a String
and a char
using ==
. Java doesn't allow that.
- This is what the compilation error about "bad operand types for
==
" is saying.
String
and char
are different types.
'Y'
and "Y"
are not the same value.
- Expressions of the form "string == char" or "char == string" are not allowed.
- You shouldn't compare strings using
==
anyway; see How do I compare strings in Java?.
So if you were just going to compare (one character) String
with a char
, there are a few ways to do it; e.g.
answer.charAt(0) == 'y'
or
Character.toString('y').equals(answer)
(In this context charAt(0)
is safe. You are using the default Scanner
delimiter, so next()
is going to return a String
with length of at least 1.)
But it would be simpler to do a String
to String
comparison:
answer.equals("y")
or
"y".equals(answer)
The latter has the advantage in some contexts that "y"
can never be null
so you will avoid possible NPEs.
Now for the logical problem. You have asked the user to respond to a (Y/N)
question. But you are actually using Scanner
to read a word (loosely speaking) so you may get one character, or more than one. Also, you are assuming that if the answer is not y
or Y
, then that means "no". But what if the user enters "yes"
... or "fish"
? There are more possible answers to consider than the ones that you are expecting.
If I was marking this exercise, I would deduct a mark or two (out of ten) for not properly validating the user's input.