我是 Java 的初学者,我正在创建一个接受 Java 中用户输入的程序,并且我正在尝试创建一个接受字符串或整数作为响应的字符串。但是,当我输入可接受的整数时,它不会识别答案。这是代码:
System.out.println("How much time you you want to spend on this? Less than 30 mins, less than an hour, or more? Type \"30\", \"h\", or \"m\".");
String ls = console.next();
while (!ls.equalsIgnoreCase("h") && !ls.equalsIgnoreCase("m") && ls.equalsIgnoreCase("30")) {
System.out.println("Type shit properly.");
ls = console.next();
}
if (ls.equalsIgnoreCase("30")) {
System.out.println("Do you want to do something fun? Y/N.");
String dare = console.next();
while (!dare.equalsIgnoreCase("y") && !dare.equalsIgnoreCase("n")) {
System.out.println("Seriously?");
dare = console.next();
}
}
每次我在控制台中输入 30 时,它都会给我错误报告“正确输入”,而不是继续执行“if ls equals 30”部分。它适用于 m 和 h 选项,但不适用于数字。我认为字符串也接受数字;我错了吗?如何让它接受字符串和整数作为输入?
最佳答案
改变
&&ls.equalsIgnoreCase("30")
至
&&!ls.equalsIgnoreCase("30")
或如果您想允许任何号码,您可以使用 String.matches(String)
&&!ls.matches("\\d+")
关于java - 在 Java 中如何获取字符串输入以接受可能的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33950117/