Kann mir jemand helfen mit meinem Java 2 Fragen habe ich.1, ist zu versuchen, catch 2, wo man ein Stück code

StackOverflow https://stackoverflow.com/questions/1633763

  •  06-07-2019
  •  | 
  •  

Frage

Ich habe ein Stück von Codierung ich arbeite für eine Zuordnung zur uni und in Wahrheit bin ich nicht so der große mit Java, aber ich habe versucht,.Ich versuche, mein try-catch zu arbeiten, aber es scheint nie das zu tun, was es ist suppoes zu.Ich glaube, ich habe die Ausnahme falsch, aber ich bin nicht sicher, ob die Ausnahme für das problem, wie ich bin versucht zu stoppen Buchstaben eingegeben wird, und einfach nur zahlen.

Das Letzte problem das ich habe ist, ich weiß nicht, wo dieses Stück Kodierung:

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

Ich bin mir nicht sicher, in welchem Teil es ist suppoes zu gehen.

Jede Hilfe wäre sehr appricated.

Dies ist mein code, ich bin sorry, wenn es ist ein wenig chaotisch.Codierung

War es hilfreich?

Lösung

Ihr code ist sehr ausführlich - die meisten Kommentare sind unnötig (obwohl Sie möglicherweise aufgefordert werden, schließen Sie Sie) So statt:

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

Könnten Sie schreiben:

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

minutes = MINUTES_PER_HOUR * hours;

Wenn Sie den code aufgeräumt werden es viel einfacher zu sehen, die Logik.

Andere Tipps

Ich rate Ihnen, zu lernen, zu benutzen in der IDE-debugger.Es gibt einige großartige Kostenlose tutorial-videos hier.

Mit dem debugger Sie nicht mehr haben, um println alle Aussagen über Ihren code.

Wirklich, nehmen Sie sich die Zeit.

Try/catch wahrscheinlich tut Arbeit

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

aber Sie fallen durch, um die code, die verarbeitet dann die Eingabe unabhängig.Sie brauchen, um beenden Sie das Unterprogramm in Ihre catch block und Prozess die gültige Eingabe in der try block.z.B.

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
 }

Hier ist der fix.Ernsthaft, ich dachte, Ihr würde es nicht funktionieren.Aber ich formatiert es in meiner IDE und nur Hinzugefügt, die eine main-Methode zum aufrufen Ihrer cancel () - Methode.Es funktionierte.

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

Einige Allgemeine Kommentare.

Sollten Sie ein Großteil des Codes aus der Time () - Konstruktor, und in einer main-Methode.Dieser code hat nichts zu tun mit der Instanziierung einer Zeit-Objekt.

Ihre while-Schleife sollte, schließen Sie alle, die Sie möchten, zu wiederholen.In diesem Fall wird der Benutzer aufgefordert, das für eine Abfahrt Zeit Ankunft Zeit, und die Berechnung der Differenz.

Sie haben duplizierten code, warum nicht eine Methode, um Fragen der Nutzer zur Eingabe einer Uhrzeit-Zeichenfolge und analysieren es.So etwas wie

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

Ok, ich habe es herausfinden, jetzt :) nach ein wenig Schlaf und am frühen morgen und vorsichtig denken.

First off, ich habe alle wichtigen Dinge tun, in Methoden zu befreien, mein Konstruktor Bereich, wie so viele von Euch mir gesagt haben, und ich Stimme ja es ist so viel einfacher, um zu sehen, was ist Los jetzt.

Lösen Sie den try catch Problem.Ich realisierte, dass ich heute morgen war, dass es in der falschen Stelle, und es war nicht versucht, was ich wollte, es zu versuchen, und die wichtigsten Linie wollte ich es versuchen, bedeutete, dass ich meine andere Codierung drinnen war es auch gut und die catch-Anweisung endet jetzt, wenn es ist hit.Ich muss nur herausfinden, wie eine Schleife es wieder Rum, anstatt zu beenden.

Lösen meine andere Frage, was war die cancel-Taste, die ich verwendet, die while (true) statement und auch steckte es in wo die JOptionPane war auch, als das war, das nur 2 Plätze Abbrechen gedrückt werden könnte...Ich weiß nicht, ob das der richtige also, wenn jemand kann mir sagen, ob es (oder, noch besser, ich werde es in jenen Orten)

So, hier ist der Arbeitscode, es gibt noch ein paar bugs drin, wie ich Sie habe, um herauszufinden, wie es zu begrenzen, nur hh.mm, im moment kann ich in jeder x-beliebigen Zeit.Ich muss auch herausfinden, wie Sie zu behandeln von 24 Stunden mit 00 Zeit es sich nicht umgehen, dass in dem moment, es ist auch nicht wie es, wenn Sie setzen 12.00 Uhr und 3.00 entweder es kommt mit -9 oder was auch immer, es hat funktioniert es wieder, die zum verwalten von 24 Stunden, und die Letzte, kleine Sache, es ist falsch es ist, dass, wenn Sie Fehler, wird es in der Nähe statt Schleife, die ich versuchen werden, zu Sortieren out now.

Codierung

Vielen Dank für die Hilfe aller in der letzten Nacht, die Sie alle haben mir geholfen so viel

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top