【发布时间】: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