String input problems?

2019-09-10 03:32发布

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.

4条回答
smile是对你的礼貌
2楼-- · 2019-09-10 03:48

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--;
  }
查看更多
迷人小祖宗
3楼-- · 2019-09-10 03:53

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.

查看更多
男人必须洒脱
4楼-- · 2019-09-10 03:55

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

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-09-10 04:02

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

查看更多
登录 后发表回答