Qualcuno può aiutare con i miei 2 problemi Java che ho. 1 è provare catch 2 è dove inserire un pezzo di codice

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

  •  06-07-2019
  •  | 
  •  

Domanda

Ho un pezzo di codice su cui sto lavorando per un incarico per uni e in verità non sono eccezionale con Java, ma ci ho provato. Sto cercando di far funzionare il mio tentativo ma non sembra mai fare ciò che dovrebbe. Penso di avere l'eccezione sbagliata, ma non sono sicuro dell'eccezione da utilizzare per il problema, poiché sto cercando di impedire la digitazione delle lettere e solo i numeri.

L'ultimo problema che sto avendo è che non so dove mettere questo pezzo di codifica:

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

Non sono sicuro in quale parte dovrebbe andare.

Qualsiasi aiuto sarebbe molto apprezzato.

Questo è il mio codice, mi dispiace se è un po 'disordinato. Coding

È stato utile?

Soluzione

Il tuo codice è molto dettagliato - la maggior parte dei commenti non sono necessari (anche se potresti essere invitato a includerli) Quindi invece di:

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

Potresti scrivere:

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

minutes = MINUTES_PER_HOUR * hours;

Dopo aver riordinato il codice sarà molto più semplice vedere la logica.

Altri suggerimenti

Ti consiglio di imparare a usare il debugger del tuo IDE. Ci sono alcuni fantastici video tutorial gratuiti qui .

Con il debugger non dovrai più inserire println su tutto il tuo codice.

Davvero, prenditi il ??tempo.

Il tuo try / catch probabilmente funziona funziona

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

ma cadi nel codice che quindi elabora l'input indipendentemente . È necessario uscire dalla subroutine nel blocco catch ed elaborare l'input valido nel blocco try . per es.

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
 }

Ecco la correzione. Seriamente, per prima cosa ho pensato che non avrebbe funzionato. Ma l'ho formattato nel mio IDE e ho appena aggiunto un metodo principale per chiamare il tuo metodo cancel (). Ha funzionato.

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

Alcuni commenti generali.

Dovresti spostare la maggior parte di questo codice fuori dal costruttore Time () e in un metodo principale. Questo codice non ha nulla a che fare con l'istanza di un oggetto time.

Il tuo ciclo while dovrebbe racchiudere tutto ciò che vorresti ripetere. In questo caso, chiedere all'utente un orario di partenza, un orario di arrivo e calcolare la differenza.

Hai un codice duplicato, perché non hai un metodo per chiedere all'utente di inserire una stringa temporale e analizzarla. Qualcosa come

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, l'ho capito ora :) dopo un po 'di sonno, la mattina presto e un'attenta riflessione.

Prima di tutto ho messo tutte le cose importanti da fare nei metodi per liberare la mia area di costruzione come molti di voi mi hanno detto di fare e sì, sono d'accordo che è molto più facile vedere cosa sta succedendo ora.

Per risolvere il problema del tentativo di cattura. Mi sono reso conto stamattina che lo stavo mettendo nel posto sbagliato e non stava provando quello che volevo che provasse e la linea principale che volevo che provasse significava che dovevo inserire l'altro mio codice al suo interno era buono e la dichiarazione di cattura ora termina se viene colpito. Devo solo scoprire come riavvolgerlo invece di terminare.

Per risolvere il mio altro problema, che era il pulsante Annulla, ho usato l'istruzione while (true) e l'ho inserito anche dove era JOptionPane in quanto erano gli unici 2 posti in cui si poteva premere Annulla ... sapere se quello è giusto, quindi se qualcuno può dirmi se lo è (o meglio ancora lo commenterò in quei posti)

Quindi ecco il codice funzionante, ci sono ancora un paio di bug come se dovessi scoprire come limitarlo a solo hh.mm poiché al momento posso inserire qualsiasi tempo casuale. Devo anche trovare come gestire 24 ore con 00 in quanto non lo gestisce affatto al momento, inoltre non gli piace se metti 12.00 e 3.00 o viene fuori con -9 o qualunque cosa abbia funzionato per essere, ancora una volta si tratta di gestire 24 ore e l'ultima piccola cosa che ha di sbagliato è che se lo sbagli, si chiuderà piuttosto che loop che cercherò di risolvere ora.

Coding

Grazie per l'aiuto di tutti ieri sera mi avete aiutato così tanto

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top