Hot questions for Using JTextField in try catch

Question:

I am working on 2 programs for school, one to take contact info and save it to a text file and the other is to read from the text file. All works perfectly but I have to add a try/catch block the program that takes input so that it would catch non-numeric entries in the age text field. I have been trying many different ways of doing this since yesterday and nothing has been working. Below is the code. If someone can point me in the right direction I would be very grateful because I feel like there is something fundamental I am not getting here. Thanks

  private class SaveData implements ActionListener{
    public void actionPerformed(ActionEvent e){

            String age1 = (String)ageField.getText();
            int age = Integer.parseInt(age1);

            try{
                int a = age;
            }
            catch(InputMismatchException e1){
                JOptionPane.showMessageDialog(null, "Please enter an     Integer");
            }

            String name = (String)nameField.getText();
            String email = (String)emailField.getText();
            String cell = (String)cellField.getText();  

            if(age>= 0 && age<=120){
                outputFile.println("Name: " + name);
                outputFile.println("Age: " + age);
                outputFile.println("Email: " + email);
                outputFile.println("Cell #: " +cell);
                outputFile.println("---------------------------");

                nameField.setText("");
                ageField.setText("");
                emailField.setText("");
                cellField.setText("");
            }
            else{
                JOptionPane.showMessageDialog(null, "You have entered an invalid age \n " +
                                        "Please enter an age between 0 and 120",
                                                "Age Entry Error",      JOptionPane.ERROR_MESSAGE);

                nameField.setText("");
                ageField.setText("");
                emailField.setText("");
                cellField.setText("");
            }//end else
        }//end actionperformed
    }//end actionlistener

Answer:

Simply write down int age = Integer.parseInt(age1); these lines inside try/catch block and catch for NumberFormatException Exception.

Question:


Answer:

I assume your code isn't working?

The way I'd do it is to create a Boolean method and return true or false

boolean checkIfNumber(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(null, "Enter a number!");
        return false;
    }
    return true;
}

Edit:

What I'd do in this situation is, surround whatever code you are doing with an if statement calling the boolean method:

if (checkIfNumber(txtWeight.getText())) {
     //do your code here
} else {
     //do something else if necessary if the return is false
}

Question:

I'm new in Java and I'm now trying to create a program that receive value from user using JTextfield and use the value to perform some calculation. I've encountered a problem that the JTextfield will have NumberFormatException Error when I trying to compile it. Here is my code:

import javax.swing.*;
import java.lang.*;
public class VehicleParking {
   public static void main(String args[]) {
      JTextField inh = new JTextField(2);
      JTextField inm = new JTextField(2);
      JTextField outh = new JTextField(2);
      JTextField outm = new JTextField(2);

      JPanel InPanel = new JPanel();
      InPanel.add(new JLabel("In Hours: "));
      InPanel.add(inh);
      String inhour = inh.getText();
      double inhourInput = Double.valueOf(inhour);
      InPanel.add(Box.createHorizontalStrut(15));
      InPanel.add(new JLabel("Minutes :"));
      InPanel.add(inm);
      String inminute = inm.getText();
      double inminuteInput = Double.valueOf(inminute);

      JPanel OutPanel = new JPanel();


      OutPanel.add(new JLabel("Out Hours: "));
      OutPanel.add(outh);
      String outhour = outh.getText();
      double outhourInput = Double.valueOf(outhour);
      OutPanel.add(Box.createHorizontalStrut(15));
      OutPanel.add(new JLabel("Minutes :"));
      OutPanel.add(outm);
      String outminute = outm.getText();
      double outminuteInput = Double.valueOf(outminute);

And here is what i get when i try to compile it:

Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.lang.Double.valueOf(Double.java:502)
    at VehicleParking.main(VehicleParking.java:23)

There're more at the bottom for display and arithmetic purpose. Also, I've tried to use the try and catch, but it doesn't solve my problem at all.(Even more error were shown up.) Here are my full program after using the try and catch to try to solve the Number Format Exception problem.(I know it's somehow too long for such simple arithmetic program. Sorry.)

import javax.swing.*;
import java.lang.*;
public class VehicleParking {
   public static void main(String args[]) {
      JTextField inh = new JTextField(2);
      JTextField inm = new JTextField(2);
      JTextField outh = new JTextField(2);
      JTextField outm = new JTextField(2);

      JPanel InPanel = new JPanel();
      InPanel.add(new JLabel("In Hours: "));
      InPanel.add(inh);
      InPanel.add(Box.createHorizontalStrut(15));
      InPanel.add(new JLabel("Minutes :"));
      InPanel.add(inm);

      JPanel OutPanel = new JPanel();


      OutPanel.add(new JLabel("Out Hours: "));
      OutPanel.add(outh);
      OutPanel.add(Box.createHorizontalStrut(15));
      OutPanel.add(new JLabel("Minutes :"));
      OutPanel.add(outm);




      int choice = JOptionPane.showConfirmDialog(null, InPanel, "Vehicle Parking System",JOptionPane.OK_CANCEL_OPTION);
            if (choice == JOptionPane.OK_OPTION)
                {
                    try
                        {String inhour = inh.getText();
                        double inhourInput = Double.valueOf(inhour);}
                    catch (NumberFormatException e){
                        if (inhour == null || inhour.equals(""))
                            {inhourInput = 0.0;}
                        else
                            {inhourInput = 0.0;}}


                    try
                        {String inminute = inm.getText();
                        double inminuteInput = Double.valueOf(inminute);}
                    catch (NumberFormatException e){
                        if (inminute == null || inminute.equals(""))
                            {inminuteInput = 0.0;}
                        else
                            {inminuteInput = 0.0;}}

                    int choice2 = JOptionPane.showConfirmDialog(null, OutPanel, "Vehicle Parking System",JOptionPane.OK_CANCEL_OPTION);
                    if (choice2 == JOptionPane.OK_OPTION)
                        {
                            try
                                {String outhour = outh.getText();
                                double outhourInput = Double.valueOf(outhour);}
                            catch (NumberFormatException e){
                                if (outhour == null || outhour.equals(""))
                                    {outhourInput = 0.0;}
                                else
                                    {outhourInput = 0.0;}}

                            try
                                {String outminute = outm.getText();
                                double outminuteInput = Double.valueOf(outminute);}
                            catch (NumberFormatException e){
                                if (outminute == null || outminute.equals(""))
                                    {outminuteInput = 0.0;}
                                else
                                    {outminuteInput = 0.0;}}
                        double hour = outhourInput - inhourInput;
                        double minute = outminuteInput - inminuteInput;
                        String[] VehicleType = {"Car","Van","Bus","Lorry"};
                        String typeVehicle =(String)JOptionPane.showInputDialog (null, "Choose vehicle type: ","Vehicle Parking System",JOptionPane.PLAIN_MESSAGE,
                                                                                null,VehicleType,VehicleType[0]);
                        switch (typeVehicle)
                            {case "Car" :   if (minute <0)
                                                {minute = minute +60;
                                                hour = hour - 1;
                                                double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            else
                                                {double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            break;

                            case "Van"  :   if (minute <0)
                                                {minute = minute +60;
                                                hour = hour - 1;
                                                double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*120/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            else
                                                {double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*120/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            break;
                            case "Bus"  :   if (minute <0)
                                                {minute = minute +60;
                                                hour = hour - 1;
                                                double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*140/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            else
                                                {double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*140/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            break;

                            case "Lorry" :  if (minute <0)
                                                {minute = minute +60;
                                                hour = hour - 1;
                                                double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*160/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            else
                                                {double calcalateDuration = hour + (minute/60);
                                                double fee = calcalateDuration*160/100;
                                                String show = "Parking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,show,"Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                JOptionPane.showMessageDialog(null,"Please take your receipt.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);
                                                String receipt =    "In time: "+inhourInput+" "+inminuteInput+
                                                                    "\nOut time: "+outhourInput+" "+inminuteInput+
                                                                    "\nDuration: "+hour+"hours and "+minute+"minutes."+
                                                                    "\nVehicle Type: "+typeVehicle+
                                                                    "\nParking fee: "+fee;
                                                JOptionPane.showMessageDialog(null,receipt,"Vehicle Parking System - Parking Receipt",JOptionPane.INFORMATION_MESSAGE);}
                                            break;
                            default     :   JOptionPane.showMessageDialog(null,"Unknown Error Occurred!","Vehicle Parking System",JOptionPane.ERROR_MESSAGE);
                                            break;}}


                    else
                        JOptionPane.showMessageDialog(null,"Process Canceled.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);}
            else
                JOptionPane.showMessageDialog(null,"Process Canceled.","Vehicle Parking System",JOptionPane.INFORMATION_MESSAGE);



   }
}

I've been stucked here for half a day, maybe not long enough for some people. But I really do need some help. Thanks.


Answer:

In the first example, it appears the line that is causing the problem is:

double outhourInput = Double.valueOf(outhour);

The exception trace referenced indicates that outhour is empty/null. Therefore, prior to the conversion, check to see if outhour is empty (e.g., outhour != null && ! outhour.trim().isEmpty()).

Having copied the code (from the 2nd example) into an IDE, it is quickly clear where the problem is. You do not have a problem with NumberFormatException per se. The problem, which is in multiple places, is a scope issue with the variables.

       if (choice == JOptionPane.OK_OPTION) {
        try {
            String inhour = inh.getText();  //-->inhour defined here
            double inhourInput = Double.valueOf(inhour);
        }
        catch (NumberFormatException e) {
            if (inhour == null || inhour.equals("")) {  //-->no scope for inhour
                inhourInput = 0.0;
            }
            else {
                inhourInput = 0.0;
            }
        }

In all of your blocks, you must ensure that the defined variable is in scope in the catch blocks. However, I do not see the point of the if tests since they all set to the variable to 0.0 anyway.

Try an approach such as:

double inhourInput = 0.0;
String inhour = inh.getText();
try {
   inhour = inh.getText();
   inhourInput = Double.valueOf(inhour);
}
catch (NumberFormatException e) {
  // do not really need to reset to 0, but can be useful for clarity
  inhoutInput = 0.0;
}