输入字符串中的格式异常(Java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16097443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format Exception in input string (Java)
提问by user2213611
I am writing an appointment program in Java and am coming across an error which is "Exception in thread "main" java.lang.NumberFormatException: For input string : "quit" " For the following lines :
我正在用 Java 编写约会程序,但遇到一个错误,即“线程“main”中的异常 java.lang.NumberFormatException: For input string : “quit” “ 对于以下几行:
Exception in thread "main" java.lang.NumberFormatException: For input string: "quit"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at AppointmentNew.main(AppointmentNew.java:24)
Also, when I make the selection in my code of printing a range of dates that the user inputs in the program it is printing out nothing, it is just going to the next line of "Make Choice ( 1: New, 2: Print Range, 3: Print All, quit):" It should print out the range of dates that the user inputs...
此外,当我在我的代码中选择打印用户在程序中输入的日期范围时,它什么也不打印,它只会转到“ Make Choice ( 1: New, 2: Print Range , 3: Print All, quit):" 应该打印出用户输入的日期范围...
Here is the code I have :
这是我的代码:
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================");
do
{
System.out.print("\n\tMake Choice (1: New, 2: Print Range, 3: Print All, 4: Quit) ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
stdin.nextLine();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = (date + " : \"" + descrip + "\", " + typeChose);
list.add(stringToAdd);
System.out.println("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
if (currentDate.compareTo(lowDate) >= 0 && currentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println("\n\t" + list.get(i));
}
}
}while (choiceNum != 4);
}
}
Thank you in advance for any advice or help that is given!
预先感谢您提供的任何建议或帮助!
回答by Sanchit
What you need to do is change the way you get input. I'm not going to change the logic in your code so just use this method instead.
你需要做的是改变你获得输入的方式。我不会更改您代码中的逻辑,因此只需使用此方法即可。
public static Integer getNextInteger(Scanner stdin) {
String line = null;
int parsed = 0;
while ((line = stdin.nextLine()) != null) {
try {
parsed = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
// Throw error message to user.
}
}
return parsed;
}
You could also externalize your whole menu into a function and use the return value for the rest of your code.
您还可以将整个菜单外部化为一个函数,并将返回值用于其余代码。
public int generateMenuAndGetChoice(Scanner stdin) {
System.out.println("Make Choice ( 1: New, 2: Print Range, 3: Print All, quit): ");
while (true) { //Keep trying until we get correct input.
String input = stdin.nextLine().trim(); // To deal with extra spaces.
if (input.equals("1") || input.equalsIgnoreCase("new")) {
return 1;
} else if (input.equals("2") || input.equalsIgnoreCase("print range")) {
return 2;
} else if (input.equals("3") || input.equalsIgnoreCase("quit")) {
return 3;
} else {
//Throw error to user possibly reshow menu options as well after error.
}
}
}
You are adding a giant string to list and then trying to get a date out of it. Moreover you are doing a String comparison with the 'dates' instead of a date comparison. This is probably why you are getting no output.
您正在向列表中添加一个巨大的字符串,然后尝试从中获取日期。此外,您正在使用“日期”而不是日期比较进行字符串比较。这可能就是您没有输出的原因。
Replace everywhere you get a date such as below:
替换您获得日期的所有位置,如下所示:
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
String lowDate = stdin.nextLine();
with this:
有了这个:
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
and then compare dates using Dates.compareTo().
然后使用Dates.compareTo()比较日期。
Note:that your entire program relies on CORRECT input by the user. This will most definitely not be the case. Use try-catch and the Scanners hasNextInt() and such methods to ensure that you always get correct input from the user.
注意:您的整个程序依赖于用户的正确输入。这绝对不是这种情况。使用 try-catch 和 Scanners hasNextInt() 等方法来确保您始终从用户那里获得正确的输入。
回答by Madhusudan Joshi
Here's what i think, you should modify the code as mentioned here :
这是我的想法,您应该修改此处提到的代码:
System.out.print("\n\tMake Choice ( 1: New, 2: Print Range, 3: Print All, **4: quit**): ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
Now check the while loop condition as :
现在检查while循环条件为:
while (choiceNum != 4);
This is one of the way to solve your problem. java.lang.NumberFormatException occurs when you are attempting convert a string to numeric type, but string in not in appropriate format.
这是解决您的问题的方法之一。java.lang.NumberFormatException 在您尝试将字符串转换为数字类型但字符串格式不正确时发生。
Update : The above mentioned solution will work fine if the user provide input in appropriate format. It will throw NumberFormatException if user provides any other string which not in format.To make the code error free , you can do something like this :
更新:如果用户以适当的格式提供输入,上述解决方案将正常工作。如果用户提供任何其他不符合格式的字符串,它将抛出 NumberFormatException。要使代码无错误,您可以执行以下操作:
try{
choiceNum = Integer.parseInt(choice);
}catch(NumberFormatException e){
System.out.println("Please provide correct input");
}
Then you will be able to avoid NumberFormatException.
然后您将能够避免 NumberFormatException。
回答by Deepak
choiceNum = Integer.parseInt(choice);
Here you are passing quit as an input string. So it is throwing number format on this line.
在这里,您将退出作为输入字符串传递。所以它在这一行上抛出数字格式。
回答by Bhavik Shah
For input string : "quit"
对于输入字符串:“退出”
choiceNum = Integer.parseInt(choice);
would give
会给
java.lang.NumberFormatException
since choice(="quit") is not an integer
因为 selection(="quit") 不是整数