Java中扫描程序输入的if语句

问题描述

我希望输入的代码是“拍摄”,然后显示“很好,您杀死了僵尸” 并且如果用户输入“不射击”,则会显示“哦,不,僵尸杀死了你”

这是我到目前为止所做的,但不会打印出任何内容

    public static void main(String[] args) {
        System.out.println("ZOMBIE AHEAD!");
        Scanner kb = new Scanner(system.in);
        String action1 = "shoot";
        String action2 = "don't shoot";
        String str = kb.nextLine();
        if (str == action1) {
            System.out.println("Nice,you killed the zombie!");
        } else if (str == action2)  {
            System.out.println("Oh no,the zombie killed you!");
        }
    }
}

解决方法

使用以下内容:

    public static void main(String[] args) {
        System.out.println("ZOMBIE AHEAD!");
        Scanner kb = new Scanner(System.in);
        String action1 = "shoot";
        String action2 = "don't shoot";
        String str = kb.nextLine();
        if (str.equals(action1)) {
            System.out.println("Nice,you killed the zombie!");
        } else if (str.equals(action2))  {
            System.out.println("Oh no,the zombie killed you!");
        }
    }
}

您必须使用 .equals()来比较字符串。