String input problems?

2019-09-10 03:03发布

问题:

I've looked around for a while and I couldn't find an exactly similar question. I'm writing a program that has a user choose what type of question they will be asked, then they input their answer. If they get it right, a point is added to their score. I can get it to work when the answers are incorrect, but not when they're correct. I know this is happening because the inputted strings do not match what the correct answers are stored as for some reason, but I cannot figure out why. Here's a section of the code:

System.out.println("What school do the Badgers belong to?");
mascotQuestion1 = scan.next();
if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
    score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
    score = (score + 0);
} 
else {
    score--;
}

Basically, the if and else if statements don't work. Every input is sent to the else statement. What's the problem?

EDIT: So, I tried printing the inputted mascotQuestion1 after entering "University of Michigan", and it came back "University". This is why it wrong, but I don't know how to fix this.

回答1:

If you are using the Java Scanner, you need to specify the delimiter pattern to use when looking at the tokens. I believe that it defaults to space, so when your user inputs his text, scanner.next() should retrieve the first whole word it finds.

Consider using BufferedReader, where you can use the reader.readLine() method.



回答2:

Try scan.nextLine(). I think scan.next() would only give you the next word.



回答3:

First, you do not need the "if else" because score = (score + 0) does absolutely nothing

That greatly simplifies the code to:

if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
    score++;
  } else { 
    score--;
  }


回答4:

scan.next() will simply read the next word (more specifically a token) as it uses space as a delimiter by default. You could use scan.nextLine().

But it will be better to use a BufferedReader instead of Scanner as per your requirement. It will let you read a line at once using readLine().

Here's what you can do:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("What school do the Badgers belong to?");

mascotQuestion1 = br.readLine();     

if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
    score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
    score = (score + 0);
} 
else {
    score--;
}

Refer this post for more information on Scanner and BufferedReader Scanner vs. BufferedReader