1

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 :

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

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!

8
  • 1
    your choice is not an Integer hence the exception. what input you give after the menu is printed Commented Apr 19, 2013 at 4:58
  • Like you have 1 for New, 2 for Print Range, you should provide some numeric option for quit like 0 Commented Apr 19, 2013 at 5:00
  • Don't use == and != for object equality check, use equals method instead. You can use a try/catch to handle the exception. Commented Apr 19, 2013 at 5:00
  • Is that an easy fix? Or is it fairly complicated? Commented Apr 19, 2013 at 5:00
  • choiceNum = Integer.parseInt(choice); This will throw NumberFormatException if choice is not a number. Commented Apr 19, 2013 at 5:00

4 Answers 4

2

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

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.

Sign up to request clarification or add additional context in comments.

11 Comments

What exactly does that first set of code do? And what would it replace in my code?
I don't know what he wants to do in the print range option. I'm just telling you ways to avoid the NumberFormatException. The first set of code just keeps trying until the user inputs an integer.
The user is able to input the dates of their appointments (As many as they want), after they are done inputting their appointments and dates the user should be able to press "2" and then enter a "Start Date" and an "End Date" and from that it should print out all the appointments the user inputted in that date span....
Yeah, thats work you need to do. You have two workarounds to your NumberFormatException which is what you asked for. Mark some answer as answered and then give that print range option a go on your own.
I actually had two parts in the question, FYI.
|
1

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 (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 API

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 :

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

Then you will be able to avoid NumberFormatException.

7 Comments

that worked! Do you have an idea of how to get the "Print Range" to work properly?
So, that was a right answer :) what exactly you want to do in that print range option?
The user is able to input the dates of their appointments (As many as they want), after they are done inputting their appointments and dates the user should be able to press "2" and then enter a "Start Date" and an "End Date" and from that it should print out all the appointments the user inputted in that date span....
It won't be gud to write answers to a new question which differs from the subject. So can you please ask a new question. Thanks.
Not solved. You still have that NumberFormatException if the user types something wrong. Remember: Users can - and WILL - make mistakes. This is nothing exceptional
|
0

For input string : "quit"

choiceNum = Integer.parseInt(choice);

would give

java.lang.NumberFormatException

since choice(="quit") is not an integer

Comments

0
choiceNum = Integer.parseInt(choice);

Here you are passing quit as an input string. So it is throwing number format on this line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.