You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java的if else语句中正确匹配带空格的多词字符串?

问题根源

你现在的匹配失败是Scanner的next()方法的特性导致的:next()默认以空白字符(空格、换行、制表符等)作为分隔符,只会读取输入内容里第一个空白字符之前的部分。你输入Nothing is true.时,next()实际只会拿到Nothing,自然和你写的判断条件匹配不上。

解决方法

做两处调整即可:

  • 把读取输入的inp.next()替换为inp.nextLine(),这个方法会读取整行输入,直到遇到回车换行,能完整保留输入中的空格
  • 将if判断中的匹配字符串修改为你需要的"Nothing is true."
修正后的完整代码
import java.util.Scanner; // 注意不要漏导入Scanner类

public class InputTest {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        String answer1;
        System.out.println("When men are blindly following the truth, remember...");
        answer1 = inp.nextLine();
        if (answer1.equals("Nothing is true.")) {
            System.out.println("Correct.");
        } else {
            System.out.println("Wrong.");
        }
        inp.close(); // 用完关闭输入流是良好编码习惯
    }
}

补充注意:如果你后续的代码里有先调用nextInt()、nextDouble()这类非整行读取方法的场景,这类方法会把换行符残留在输入缓冲区里,紧接着调用nextLine()会读到空字符串,这时候只要在非整行读取方法后面多调用一次inp.nextLine()吃掉残留的换行即可,你当前的代码没有这类场景,直接使用即可。

内容的提问来源于stack exchange,提问作者Mumuchim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:06:03