【发布时间】:2018-01-02 18:32:25
【问题描述】:
尝试使用 Scanner 获取 int 或 string.. 下面的代码是我所拥有的:
System.out.println("where would you like to send the following item: ");
System.out.println("1. groceries, 2. savings, 3. utilities");
System.out.print("Enter list name or list number to send: ");
String user = user_input.nextLine();
if (user.toLowerCase().equals("groceries") || Integer.parseInt(user) == 1) {
System.out.println("item was sent to the grocery list");
}else if(user.toLowerCase().equals("savings") || Integer.parseInt(user) == 2) {
System.out.println("item was sent to the savings list");
}else if(user.toLowerCase().contains("utilities") || Integer.parseInt(user) == 3) {
System.out.println("item was sent to the utilities list");
}else{
System.out.println("item is not in any category");
}
我的问题是,每当我输入字符串时,都会收到 NumberFormatException 错误。键入 int 不会给我带来任何问题。我认为使用 String user = user_input.nextLine(); 获取输入并使用 Integer.parseInt(user) 在 if 语句中将数字字符串转换为 int 可以解决问题,但它仍然给我错误消息。
非常感谢任何帮助...
【问题讨论】:
-
parseInt如果输入字符串不代表整数,则抛出NumberFormatException。见docs -
您可以避免使用
parseInt和user.equals("1")等。 -
让我澄清一下:
if (user.toLowerCase().equals("groceries") || user.equals("1")) {等 -
我很抱歉@JohnnyMopp ...我应该知道这就是您的意思...实际上确实有效...谢谢。你帮我解决了我的问题
标签: java string if-statement int java.util.scanner