¿Alguien puede ayudarme con mis 2 problemas de Java que tengo? 1 es tratar de atrapar 2 es donde poner un fragmento de código

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

  •  06-07-2019
  •  | 
  •  

Pregunta

Tengo una pieza de codificación en la que estoy trabajando para una tarea para uni y, en verdad, no soy tan bueno con Java, pero lo he intentado. Estoy tratando de que mi intento de captura funcione pero parece que nunca hace lo que se supone que debe hacer. Creo que tengo una excepción incorrecta, pero no estoy seguro de qué excepción usar para el problema, ya que estoy tratando de evitar que se escriban letras y solo números.

El último problema que tengo es que no sé dónde poner esta pieza de codificación:

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

No estoy seguro en qué parte se supone que debe ir.

Cualquier ayuda sería muy útil.

Este es mi código, lo siento si es un poco desordenado. Codificación

¿Fue útil?

Solución

Su código es muy detallado: la mayoría de los comentarios son innecesarios (aunque se le puede recomendar que los incluya) Entonces, en lugar de:

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

Podrías escribir:

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

minutes = MINUTES_PER_HOUR * hours;

Cuando haya ordenado el código, será mucho más fácil ver la lógica.

Otros consejos

Te aconsejo que aprendas a usar el depurador de tu IDE. Hay algunos excelentes videos tutoriales gratuitos aquí .

Con el depurador ya no tendrá que poner declaraciones println en todo su código.

Realmente, tómate tu tiempo.

Su intento / captura probablemente funciona

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

pero se cae al código que luego procesa la entrada independientemente . Debe salir de la subrutina en su bloque catch y procesar la entrada válida en el bloque try . por ejemplo,

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
 }

Aquí está la solución. En serio, primero pensé que tu no funcionaría. Pero lo formateé en mi IDE y acabo de agregar un método principal para llamar a su método cancel (). Funcionó.

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

Algunos comentarios generales.

Debería mover la mayor parte de este código fuera del constructor Time () y en un método principal. Este código no tiene nada que ver con crear instancias de un objeto de tiempo.

Su ciclo while debe incluir todo lo que le gustaría repetir. En este caso, pedirle al usuario una hora de salida, una hora de llegada y calcular la diferencia.

Ha duplicado el código, ¿por qué no tiene un método para pedirle al usuario que ingrese una cadena de tiempo y la analice? Algo como

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, ya lo descubrí :) después de dormir un poco y temprano en la mañana y pensar cuidadosamente.

En primer lugar, puse todas las cosas importantes en métodos para liberar mi área de construcción como muchos de ustedes me dijeron que hiciera y sí, estoy de acuerdo en que es mucho más fácil ver lo que está sucediendo ahora.

Para resolver el problema de try catch. Esta mañana me di cuenta de que lo estaba colocando en el lugar equivocado y que no estaba intentando lo que quería que intentara, y la línea principal que quería que intentara significaba que tenía que poner mi otra codificación dentro y que la declaración catch ahora termina si es golpeado. Solo necesito descubrir cómo hacer un bucle de vuelta en lugar de terminar.

Para resolver mi otro problema, que era el botón cancelar, utilicé la instrucción while (verdadero) y también la puse donde estaba JOptionPane, ya que esos eran los únicos 2 lugares donde se podía presionar cancelar ... No saber si ese es el correcto, así que si alguien puede decirme si es así (o mejor aún, lo comentaré en esos lugares)

Entonces, aquí está el código de trabajo, todavía hay un par de errores en él, como si tuviera que averiguar cómo limitarlo a solo hh.mm, ya que en este momento puedo poner un tiempo aleatorio. También necesito encontrar descubra cómo manejar las 24 horas con 00 horas, ya que no maneja eso en este momento, tampoco le gusta si agrega 12.00 y 3.00, ya sea con -9 o lo que sea que haya funcionado para ser, una vez más, se trata de administrar las 24 horas y lo último que tiene de malo es que si lo equivocas, se cerrará en lugar del ciclo que trataré de resolver ahora.

Codificación

Gracias por la ayuda de todos anoche, todos ustedes me ayudaron mucho

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top