输入字符串中的格式异常(Java)

时间:2013-04-19 04:55:00

标签: java numberformatexception

我正在用Java编写一个约会程序,我遇到一个错误,即“线程中的异常”主“java.lang.NumberFormatException:对于输入字符串:”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)

另外,当我在我的打印代码中选择用户在程序中输入的一系列日期时,它什么都没打印出来,它只是进入下一行“做出选择(1:新建,2:打印范围,3:全部打印,退出):“它应该打印出用户输入的日期范围......

这是我的代码:

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);      
 }
}

提前感谢您提供任何建议或帮助!

4 个答案:

答案 0 :(得分:2)

您需要做的是改变输入方式。我不打算更改代码中的逻辑,所以只需使用此方法。

  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;
  }

您还可以将整个菜单外部化为一个函数,并使用其余代码的返回值。

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.
    }
  }
}

您要添加一个巨大的字符串列表,然后尝试从中获取日期。此外,您正在使用'日期'而不是日期比较进行字符串比较。这可能就是你没有输出的原因。

在任何地方替换您的日期,如下所示:

System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
String lowDate = stdin.nextLine();

用这个:

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());

然后使用Dates.compareTo()比较日期。

注意:您的整个程序依赖于用户的CORRECT输入。绝对不会是这种情况。使用try-catch和Scanners hasNextInt()以及此类方法可确保始终从用户那里获得正确的输入。

答案 1 :(得分:1)

以下是我的想法,你应该修改这里提到的代码:

System.out.print("\n\tMake Choice ( 1: New, 2: Print Range, 3: Print All, **4: quit**): ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);

现在将while循环条件检查为:

while (choiceNum != 4);

这是解决问题的方法之一。 尝试将字符串转换为数字类型,但字符串格式不合适时,会发生java.lang.NumberFormatException。

Java API

更新:如果用户以适当的格式提供输入,上述解决方案将正常工作。 如果用户提供任何其他不在格式中的字符串,它将抛出NumberFormatException。为了使代码没有错误,你可以这样做:

try{
    choiceNum = Integer.parseInt(choice);
   }catch(NumberFormatException e){
        System.out.println("Please provide correct input");
   }

然后您将能够避免NumberFormatException。

答案 2 :(得分:0)

choiceNum = Integer.parseInt(choice);

这里您将quit作为输入字符串传递。所以它在这一行上抛出数字格式。

答案 3 :(得分:0)

对于输入字符串:&#34;退出&#34;

choiceNum = Integer.parseInt(choice);

会给出

java.lang.NumberFormatException

因为choice(=&#34; quit&#34;)不是整数