[英]How do I get a String input to accept a possible integer in Java?
I'm a very beginner at Java, and I'm creating a program that accepts user input in Java, and I'm trying to create a string that accepts strings or integers as responses. 我是Java的初学者,正在创建一个接受Java用户输入的程序,并试图创建一个接受字符串或整数作为响应的字符串。 However, when I type in the acceptable integer, it won't recognize the answer.
但是,当我输入可接受的整数时,它将无法识别答案。 Here is the code:
这是代码:
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();
}
}
Every time I type 30 into the console, it gives me my error report "Type shit properly" instead of proceeding to the "if ls equals 30" section. 每次我在控制台中键入30时,它都会向我显示错误报告“正确键入该死”,而不是继续执行“如果ls等于30”部分。 It works fine for the m and h options, just not the number.
它适用于m和h选项,但不适用于数字。 I thought strings accepted numbers as well;
我认为字符串也可以接受数字。 was I wrong?
我说错了吗 How do I get this to accept both Strings AND integers as input?
我如何才能接受字符串和整数作为输入?
Change 更改
&&ls.equalsIgnoreCase("30")
to 至
&&!ls.equalsIgnoreCase("30")
or if you want to allow any number, you could use String.matches(String)
或者如果您想允许任何数字,则可以使用
String.matches(String)
&&!ls.matches("\\d+")
使用!ls.matches("30")
代替ls.equalsIgnoreCase("30")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.