![](/img/trans.png)
[英]How do I accept a command and a filename in the same input string in java?
[英]How do I get a String input to accept a possible integer in Java?
我是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时,它都会向我显示错误报告“正确键入该死”,而不是继续执行“如果ls等于30”部分。 它适用于m和h选项,但不适用于数字。 我认为字符串也可以接受数字。 我说错了吗 我如何才能接受字符串和整数作为输入?
更改
&&ls.equalsIgnoreCase("30")
至
&&!ls.equalsIgnoreCase("30")
或者如果您想允许任何数字,则可以使用String.matches(String)
&&!ls.matches("\\d+")
使用!ls.matches("30")
代替ls.equalsIgnoreCase("30")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.