Results 1 to 7 of 7
  1. #1
    Masamune1059 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Unhappy try and catch problem

    In this program im using JOptionPanes and if you press cancel it should take you back to the previous one using try and catch for NullPointerExceptions. My problem is, once i go into the nested try and click back it takes me back fine, but when i press back again to get back to the main menu it goes forward instead of backward. I used print lines to determine that it isn't entering the catch for the first try, but i can't figure out why. If anyone could take a look and explain why it isn't working, and how i could rectify it i would really appreciate the help.

    Below is the code for the object im currently working on, and a link to the full netbeans project just incase you need to look elsewhere.

    MEGAUPLOAD - The leading online storage and file delivery service

    Java Code:
    package progfundass2;
    // author S0199375
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    public class Greaterthanlessthan
    {
       String[] routecode = new String[]
       {
          "EA101", "EA101", "AE101", "AE101", "PA102", "PA102", "AP102", "AP102", "IA103", "IA103", "AI103", "AI103", "FA104", "FA104", "FA104", "AF104", "AF104", "AF104", "IC105", "IC105", "CI105", "CI105", "EC106", "EC106", "CE106", "CE106", "FN107", "FN107", "FN107", "NF107", "NF107", "NF107",
       };
       String[] depart = new String[]
       {
          "London", "Paris", "La Vella", "Paris", "Lisbon", "Madrid", "La Vella", "Madrid", "Rome", "Monte Carlo", "La Vella", "Monte Carlo", "Paris", "Bern", "Vaduz", "Vienna", "Vaduz", "Bern", "Rome", "Vienna", "Prague", "Vienna", "London", "Berlin", "Prague", "Berlin", "Paris", "Amsterdam", "Brussels", "Luxembourg", "Brussels", "Amsterdam",
       };
       String[] departt = new String[]
       {
          "10.05", "11.30", "13.47", "15.50", "10.44", "12.08", "13.45", "15.24", "10.45", "12.25", "13.50", "15.00", "09.30", "10.45", "11.50", "13.00", "14.10", "15.20", "10.20", "13.05", "14.00", "14.45", "10.30", "13.02", "13.55", "14.30", "11.25", "12.25", "13.02", "13.35", "14.05", "14.43",
       };
       String[] arrivet = new String[]
       {
          "11.18", "13.24", "15.41", "17.03", "11.56", "13.21", "15.12", "16.36", "12.08", "13.27", "14.52", "16.23", "10.26", "11.26", "12.42", "13.52", "15.02", "16.16", "12.45", "13.37", "14.32", "17.10", "12.47", "13.29", "14.22", "16.47", "12.19", "12.57", "13.27", "14.00", "14.37", "15.45",
       };
       public Greaterthanlessthan()
       {
          // Loops until the program hit's a break;
          int loop = 0;
          while (loop == 0)
          {
             try
             {
                String result = "";
                //Changes JOptionPane Buttons
                UIManager.put("OptionPane.cancelButtonText", "Return to Main Menu");
                UIManager.put("OptionPane.okButtonText", "Continue");
                // User selects weather they wanter Greater or lesser
                Object menu = JOptionPane.showInputDialog(null, "Please select weather you'd like to search greater \n than or less than the time your going to input", "EuroTrans", JOptionPane.QUESTION_MESSAGE, null, new String[]
                   {
                      "Greater than", "Less than"
                   }, "Greater than");
                try
                {
                   //Changes JOptionPane Buttons
                   UIManager.put("OptionPane.cancelButtonText", "Return to previous Menu");
                   UIManager.put("OptionPane.okButtonText", "Continue");
                   // User inputs the amount of time
                   double time = Double.parseDouble(JOptionPane.showInputDialog("Input your selected amount of time in the format HH.MM"));
                   // Print line for testing
                   System.out.println(time);
                   // Turns the input number into a total amount of mins
                   int comparison = calculate(time);
                   // Print line for testing
                   System.out.println(comparison);
                   // loops through the array data
                   for (int i = 0; i < departt.length; i++)
                   {
                      // grabs depart time and turns it into a total in mins                  
                      int d = calculate(Double.parseDouble(departt[i]));
                      // grabs arrive time and turns it into a total in mins   
                      int a = calculate(Double.parseDouble(arrivet[i]));
                      // Calculates the Total time of the journey in mins
                      int journey = (a) - (d);
                      /* If the total Journey time is a negative (due to going
                       * over to the next day) this will add 1440 mins (1day) to
                       * the negative to form the correct journey time
                       */
                      if (journey <= 0)
                      {
                         journey = (journey + 1440);
                      }
                      // Calculates the amount of hours in the total journey
                      int journeyh = journey / 60;
                      /* Calculates the amount of minites remaining. Divides that by 
                       * 100 to make it a decimal. Then adds the amount of hours(journeyh)
                       * to form a total journey time in the same format as the inputs
                       */
                      double journeyt = ((double) (journey % 60)) / 100 + journeyh;
                      // If the User selected greater than
                      if (menu.equals("Greater than"))
                      {
                         // and if the journey time is greater than or equal too the time they input then add data to results
                         if (journeyt >= comparison)
                         {
                            // defines number format
                            NumberFormat form = new DecimalFormat("#00.00");
                            // adds message to results
                            result = result + routecode[i] + " from " + depart[i] + " lasts " + form.format(journeyt) + ". (HH.MM) \n";
                         }
                      }
                      // If the User selected less than
                      else if (menu.equals("Less than"))
                      {
                         // and if the journey time is less than or equal too the time they input then add data to results
                         if (journeyt <= comparison)
                         {
                            // defines number format
                            NumberFormat form = new DecimalFormat("#00.00");
                            // adds message to results
                            result = result + routecode[i] + " from " + depart[i] + " lasts " + form.format(journeyt) + ". (HH.MM) \n";
                         }
                      }
                   }
                   if (result.equals(""))
                   {
                      JOptionPane.showMessageDialog(null, "No matches where found");
                   }
                   else
                   {
                      JOptionPane.showMessageDialog(null, result);
                   }
                }
                //Catches the Cancel or X button being pressed and takes user back to the main menu.
                catch (NullPointerException cancelpress2)
                {
                   System.out.println("Cancel or X cancelpress2");
                }
                // Catches input errors (characters instead of numbers) when trying to convert the strings into doubles
                catch (NumberFormatException oninput)
                {
                   JOptionPane.showMessageDialog(null, "You have entered the time incorrectly. \n Please use the format HH.MM");
                }
             }
             //Catches the Cancel or X button being pressed and takes user back to the main menu.
             catch (NullPointerException cancelpress)
             {
                System.out.println("Cancel or X cancelpress");
                break;
             }
          }
       }
       private int calculate(double a)
       {
          // Print lines for use of testing
          System.out.println("Calculate Method.  a = " + a);
          /* If a is less that 1 both b and c are returned as 0. Although though b
           * should be 0, c should have a figure.
           */
          if (a < 1)
          {
             /* When input times where less that 1.00 they would return 0 for both b
              * and c even if this was incorrect so inserted this if statement to rectify the problem
              */
             int d = (int) (a * 100);
             // Print lines for use of testing
             System.out.println("Calculate Method.  a was less that 1.  d = " + d);
             // returns d
             return d;
          }
          else
          {
             /* Converts time to a int to be left with just hours then times that by 60
              * to get a total ammount in mins
              */
             int b = (int) (a) * 60;
             // Print line for the use of testing
             System.out.println("Calculate Method.  b = " + b);
             /* Removes the hours then times the remainder by 100 to turn the decimal
              * into a int.  Also uses Math.round to remove any inaccuracys when
              * dealing with doubles in this way
              */
             int c = (int) Math.round(a % (b / 60) * 100);
             // Print line for the use of testing
             System.out.println("Calculate Method.  c = " + c);
             // Returns B and C
             return b + c;
          }
       }
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default Re: try and catch problem

    Please post the contents of the console that shows the print outs that traced how the program was executing.
    To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.


    You should NOT be catching NullPointerExceptions. Your code should not be getting them. If you are getting nul values there is something wrong with your code that needs to be fixed.

    How is the posted code executed for testing? I don't see a main method.

    Your problem sounds like a logic flow problem. The code looks too big for anyone to want to work with. Try making a small simple program that you can post that compiles and executes and shows the problem (SSCCE).
    Last edited by Norm; 01-08-2012 at 02:08 AM.

  3. #3
    Masamune1059 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Default Re: try and catch problem

    im not entirely sure what you mean as i dont use command prompt i just run it from inside netbeans. but the output box on netbeans say
    run:
    List departures with a journey time greater than or less than a given amount of time 4
    Cancel or X cancelpress2
    Cancel or X cancelpress2
    BUILD STOPPED (total time: 46 seconds)
    a run down of what happens is as follows:

    I Click run
    The first JOptionPane from the Main pops up, and i select the option which bring me to this object
    then a 2nd pops up asking if i would like to select greater than or less than
    i select either of these and a 3rd JOptionPane appers
    i click the cancel button (which i renamed to Return to previous Menu)
    and it takes be back to the 2nd JOptionPane
    Now i click cancel again (which i renamed to Return to Main menu) but instead of going back to the 1st JOptionPane, it goes to the 3rd one, completly missing out the catch for nullpointerexception and the break; within it.

    If i click cancel (return to main menu) on the 2nd Pane before going to the 3rd it works properly and goes back to the 1st pane.

    ---EDIT---

    the build stoped is because i told the program to stop, not because it ended itself or crashed or anything like that.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default Re: try and catch problem

    Add some more printns to show where the execution flow goes and what the values of the variables are that control the loop.

    What line is the exception happening on? What variable is null? Why does the code try to use a null variable?

  5. #5
    Masamune1059 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Default Re: try and catch problem

    Ok, so it runs through fine to line 38, where you select a option from the dropdown menu provided, if you click cancel or the red X on this window it returns a null value and drops down to the catch on line 125, which inturn breaks out the loop and returns to the main menu as it should.

    The problem is, if you select a value on line 38 it then moves on to line 48 where you have to input a value. If you click cancel here, it drops down to the catch on line 114, which returns it to the start of the loop, and thus line 38 again. this is where the problem occurs, if you click cancel again, it should return a null value and drop down to the catch on line 125, but it doesn't, it seems to go to line 48 again.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default Re: try and catch problem

    What line is the exception happening on? What variable is null? Why does the code try to use a null variable?

    Your description of the problem sounds like you need to take a piece of paper and work out the logic for your code to get it to do what you want.

  7. #7
    Masamune1059 is offline Member
    Join Date
    Jan 2012
    Posts
    8
    Rep Power
    0

    Default Re: try and catch problem

    ok, i fixed it, just needed to add a line saying
    String menus = menu.toString();
    between line 41 and 42 and redirect everything that was looking for menu to menus

    Thanks anyways Norm

Similar Threads

  1. try catch problem
    By g123456 in forum New To Java
    Replies: 8
    Last Post: 05-17-2010, 06:54 PM
  2. try catch help
    By vividcooper in forum New To Java
    Replies: 8
    Last Post: 02-11-2010, 09:00 AM
  3. Problem JOptionPane try catch
    By jason99 in forum New To Java
    Replies: 1
    Last Post: 07-10-2009, 10:39 PM
  4. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 10:54 AM
  5. Try Catch
    By Renegade85 in forum New To Java
    Replies: 4
    Last Post: 12-03-2007, 04:10 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •