【问题标题】:If statement skips to elseif 语句跳到 else
【发布时间】:2019-08-19 08:43:09
【问题描述】:

我是来自 Python 的 Java 新手,所以请原谅我的迟钝。我正在尝试制作一个简单的 if 语句,但它不起作用:(。它忽略了 if 语句并直接进行其他操作。

我尝试在 if 语句中使用 .contains 和 .equalsIgnoreCase。

package me.johnminton;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);

        String species_animal;
        System.out.println("Please enter your species: ");
        species_animal = user_input.next();

        if (species_animal.contains("Erectus")) {
            System.out.println("random input statement");


        }
        else
            {
            System.out.println("okay");
        }
    }
}

如果我在第一个输入中输入 Erectus,我希望它输出“随机输入语句”。但相反,它直接进入 else 并输出“okay”。

【问题讨论】:

  • if 语句看起来没问题,尝试打印您的变量species_animal 以查看它被分配到什么。顺便说一句,您的代码对我有用。
  • 这看起来是您的扫描仪的问题,实际上。尝试改用input.nextLine()
  • 代码,至少您向我们展示的部分......有效。您没有向我们展示的代码是什么?
  • 如果您想与 Erectus 完全匹配,请尝试使用 equals 或 equalsignorecase 字符串方法而不是 contains。

标签: java if-statement


【解决方案1】:

next() 方法仅从扫描器中获取一个单词,尽管您可以通过为扫描器指定分隔符来更改该行为。

在你的情况下,如果你输入 Eructussian 或类似的东西,你会得到你想要的结果,但如果你输入 Home Erectus,你不会。

我怀疑您的意思是使用nextLine() 而不是next(),后者会获取整行文本。

【讨论】:

    【解决方案2】:

    问题是您的扫描仪在没有返回键的情况下无法完成。试试‘user_input.nextLine()’而不是‘user_input.next()’

    【讨论】: