tags:

views:

180

answers:

6

I have a piece of coding I am working on for an assignment for uni and in truth I'm not that great with Java, but I have tried. I'm trying to get my try catch to work but it never seems to do what it is suppoes to. I think I have the exception wrong but I'm not sure which exception to use for the problem as I am trying to stop letters being typed in and just numbers.

The final problem I am having is I don't know where to put this piece of coding:

 {
                   while (true)
  {
   cancel();
  }
 }

I'm not sure in which part it is suppoes to go.

Any help would be greatly appricated.

This is my code, I'm sorry if it is a little messy. Coding

+2  A: 

I advise you to learn to use your IDE's debugger. There's some great free tutorial videos here.

With the debugger you no longer will have to put println statements all over your code.

Really, take the time.

JRL
I was told for my assignment work I had to do that, that and it helped me to know that what I was doing was actually right.
Sal
A: 

Your code is very verbose - most of the comments are unnecessary (even though you may be urged to include them) So instead of:

minutesfromhours = 60*minutes;
                //To change the hours into minutes by diving the hour by 60 for departure.

You could write:

public final static int MINUTES_PER_HOUR = 60;
//...

minutes = MINUTES_PER_HOUR * hours;

When you have tidied the code it will be much easier to see the logic.

peter.murray.rust
Won't that only give me the hours not the minutes?I already have it in minutes so I have 1 hour=60 minutes, I can't get it back the other way 60 minutes= 1 hour
Sal
your code reads:minutesfromhours = 60*minutes;This does not make sense. multiplying the number of minutes by 60 gives seconds.Choosing good names for variables is much more important than comments
peter.murray.rust
Yeah I have fixed that one and got the it so that there is minutes too. Took alot of stressing as I was trying to fix too many things at once. And thank you for your help it has been really helpful and I have tried to get names that are meaning, it is hard to think of them sometimes.
Sal
+1  A: 

Your try/catch probably does work

 try
 {
    depart= Double.parseDouble(departtime);
    System.out.println(depart);
 }
 catch (NumberFormatException e)
 {
     System.out.println(e.getMessage());
 }
 System.out.println("Time accepted");

but you fall through to the code that then processes the input regardless. You need to exit the subroutine in your catch block, and process the valid input in the try block. e.g.

try
 {
    depart= Double.parseDouble(departtime);
    System.out.println(depart);
    System.out.println("Time accepted");
    // do further processing here
 }
 catch (NumberFormatException e)
 {
     System.out.println(e.getMessage());
     // exit here
 }
Brian Agnew
+1  A: 

Here is the fix. Seriously, first I thought your would not work. But i formatted it in my IDE and just added a main method to call your cancel () method. It worked !! Bravo.

import javax.swing.JOptionPane;

public class Time
{
   public int difference =0;
// Stores the difference of departure and arrival time.

   public static void main(String args [])
   {
       Time obj=new Time();

            while (true)

              obj.cancel();

   }

public Time()
    {
      String departtime = JOptionPane.showInputDialog("Enter Depart Time in 24 hour time:");
// Allows the user to input their departure time into a JOptionPane.
      String arrivaltime = JOptionPane.showInputDialog("Enter Arrival Time in 24 hour time:");
// Allows the user to input their arrival time into a JOptionPane.

      double depart = 0;
// Store the time the user first inputs as a double.
      double arrival = 0;
// Store the time the user inputs secondly as a double.

      int minutes = 0;
// To store the hours for departure.

      int minutes2 = 0;
// To store the minutes of departure.

      int totalminutesfordeparture = 0;
// To store the full time for departure as minutes.

      int minutesfromhours = 0;
// To store the hours as minutes for depature

     int arrivals = 0;
// To store the hours arrival.

     int arrival2 = 0;
// To store the minutes for arrival.

      int arrivalhoursasminutes = 0;
// To store the arrival hours as minutes.

      int totalminutesforarrival = 0;
// To store the full time for departure in minutes.

     int actualtimehours= 0;
// The number of hours it will take on the journey.

     int actualtimeminutes=0;
// The number of minutes it will take on the journey.






// **Start of removing the decimal for time 1 and time 2**\\
     {
         // Doesn't work
         try
         {
         depart= Double.parseDouble(departtime);
         System.out.println(depart);
         }
         catch (NumberFormatException e)
         {
             System.out.println(e.getMessage());
         }
         System.out.println("Time accepted");

         arrival= Double.parseDouble(arrivaltime);



         int time = (int)(depart*100);
            // Gets rid of the decimal point in the departure time.

         System.out.println ("Time with no decimal point "+ time);
             // Check the decimal is being removed.

         int time2=(int)(arrival*100);
             // Gets rid of the decimal point in arrival time.

         System.out.println ("Time with no decimal point "+ time2);
             // Check the decimal is being removed in arrival.

// **End of removing the decimal in the times**\\

// **Start of seperating the hours and minutes in departure time**\\
         {

             minutes2=time%100;
                 // To separate the minutes from the hours for departure.

            minutes=time/100;
                 // To seperate the hours ready to change them into minutes.

            System.out.println("Hours of departure "+ minutes);
                 // Check that the hours are seperating from the minutes for
        // departure.

            System.out.println("Minutes of departure "+ minutes2);
                // Check that the minutes are seperating from the hour for
       // departure.

           arrival2=time2%100;
                 // To separate the minutes from the hours.

            arrivals=time2/100;
                 // To seperate the hours ready to change them into minutes.

            System.out.println("Hours of arrival "+ arrivals);
                // Check that the hours are seperating from the minutes for
       // arrivals.

            System.out.println("Minutes of arrival "+ arrival2);
                // Check that the minutes are seperating from the hour for
       // arrivals.
         }
// **End of seperating the hours and minutes in departure time**\\

// **Start of hours being changed to minutes and adding it all up**\\
         {
             minutesfromhours = 60*minutes;
                // To change the hours into minutes by diving the hour by 60 for
       // departure.

             System.out.println("Hours into minutes "+ minutesfromhours);
                // Checks that the hours are being turned into minutes for
       // departure.

             totalminutesfordeparture= minutesfromhours+minutes2;
                // To add together the hour minutes and the minutes from the
       // time to give the total time in minutes for departure.

             System.out.println("Total Departure time in minutes "+ totalminutesfordeparture);
                // Checks that the hours as minutes are being added up with the
       // minutes of the time for departure.


             arrivalhoursasminutes = 60*arrivals;
                // To change the hours into minutes for arrivals by diving the
       // hours by 60 for arrivals.

             System.out.println("Hours into minutes for arrival "+ arrivalhoursasminutes);
                // Check that it is adding up the hour minutes and the minutes
       // for departure.

             totalminutesforarrival= arrivalhoursasminutes+arrival2;
                // To add together the hour minutes and the minutes from the
       // arrivals.

             System.out.println("Total arrival time in minutes "+ totalminutesforarrival);
                // Check that it is adding up the hour minutes and the minutes
       // for arrivals
         }

// **End of hours being changed to minutes and adding up**\\

// **Start of Finding the difference in minutes**\\
         {

             difference=totalminutesforarrival-totalminutesfordeparture;
                // Works out the difference of minutes by taking arrival time in
       // minutes away from the departure time in minutes.
             System.out.println("Difference "+ difference);
                // Check to see that it is taking arrival from departure.

             JOptionPane.showMessageDialog(null, "It will take " + difference);
         }
            // **End of finding the difference in minutes**\\

         // **start of not working changing minutes back to hours.**\\

         {
             actualtimehours= difference/60;
             actualtimeminutes= difference/60;

             System.out.println("It will take "+ actualtimehours);
             System.out.println("It will take "+ actualtimeminutes);


         }

     }

    }

// ** Method incase cancel button is pressed **\\
        public void cancel()
    {
        String input=JOptionPane.showInputDialog("Cancel button was pressed");
        if (input==null)
        {
                System.exit(0);
        }
        }
}

// Where does this go?

By the way... this is my first post in stackoverflow.

I have my own java blog. (http://www.sanjaal.com/java).

I sure will help answering questions here when I am free.

Kushal Paudyal
Thank you I will look at your blog as I will probably be visiting it alot. And it does work, only just I think and I have edited my coding a little and got one of my issues working thank god, I just hope I can get the try catch thing working which is the most annoying
Sal
Just so I know what you have done and I am just checking more than anything else incase I am way off the mark on how it was done with the cancel button all you did was created a new object and then recalled the cancel object? I'm just trying to double check as I'll probably have to use that again at some point.
Sal
A: 

Some general comments.

You should move most of this code out of the Time() constructor, and into a main method. This code doesn't have anything to do with instantiating a time object.

Your while loop should enclose all that you would like to repeat. In this case, asking the user for a depart time, an arrival time, and calculating the difference.

You have duplicated code, why not have a method to ask the user to input a time String, and parse it. Something like

public class Time {
    private int hours;
    private int minutes;
    etc...
}    

// in main
while (true) {
    Time departTime = askUser("depart");
    Time arriveTime = askUser("arrive");
    calculateDifference(departTime, arriveTime);
}

// elsewhere
public Time askUser(String name) {
    String theTime = JOptionPane.showInputDialog(
        String.format("Enter %s Time in 24 hour time:", name));
    Time result = parseTime(theTime, name);
    return result;
}
toolkit
Because I'm not too sure how to do it that way in truth and the tutor has gone through stuff with us but he is one of those tutors that goes through things so quickly sometimes its hard to grasp things and no time for questions. And I am trying to add methods into it, I'm just not confident with adding them in truth
Sal
A: 

Ok I've figure it out now :) after a little sleep and early morning and careful thinking.

First off I've put all the important doing stuff into methods freeing up my constructor area like so many of you told me to do and yeah I agree it's so much easier to see what is going on now.

To solve the try catch issue. I realised this morning that I was putting it in the wrong place and it wasn't trying what I wanted it to try and the main line I wanted it to try meant I had to put my other coding inside it was well and the catch statement now ends if it's hit. I just need to find out how to loop it back around instead of ending.

To solve my other issue which was the cancel button I used the while (true) statement and also put it in where the JOptionPane was also as that was the only 2 places the cancel could be pressed... I don't know if that one is right so if someone can tell me if it is (or better still I'll comment it out in those places)

So here is the working code, there's still a couple of bugs in it like I have to find out how to limit it to just hh.mm as at the moment I can put any random time in. I also need to find out how to handle 24 hours with 00 time as it doesn't handle that at all at the moment, it also doesn't like it if you put 12.00 and 3.00 in either it comes up with -9 or whatever it has worked it out to be, again that is about managing 24 hours and the last small thing it has wrong with it is that if you error it, it will close rather than loop which I will be trying to sort out now.

Coding

Thank you for everyone's help last night you all helped me so much

Sal