Query about java variables

1

The problem is that it does not let me call the variables of hora1 , minuto1 and segundo1 at the end of the method to make the impression

import javax.swing.JOptionPane;

public class menus {
    public menus(){

    }

    public void tiempo(){

        while (true) {
            String hora = JOptionPane.showInputDialog("Digite una hora que no exceda las 24");
            int hora1 = Integer.parseInt(hora);
            if(hora1 > 24){
                JOptionPane.showMessageDialog(null,"Las horas no pueden ser mayores a 24","Error",JOptionPane.ERROR_MESSAGE);
            }
            else{
                break;
            }
     }   

        while (true) {
            String minutos = JOptionPane.showInputDialog("Digite los minutos que no excedan los 59");
            int minutos1 = Integer.parseInt(minutos);
            if(minutos1 > 59){
                JOptionPane.showMessageDialog(null,"Los minutos no pueden ser mayores a 59","Error",JOptionPane.ERROR_MESSAGE);
            }
            else{
                break;
            }
     }
        while (true) {
            String segundos = JOptionPane.showInputDialog("Digite los segundos que no excedan los 59");
            int segundos1 = Integer.parseInt(segundos);
            if(segundos1 > 59){
                JOptionPane.showMessageDialog(null,"Los segundos no pueden ser mayores a 59","Error",JOptionPane.ERROR_MESSAGE);
            }
            else{
                break;
            }
     }  
        JOptionPane.showMessageDialog(null,"La hora es:"+hora1+"con"+minutos1+ "minutos con "+segundos1+" segundos");
    }
    
asked by Luis David Jimenez 28.05.2017 в 06:25
source

1 answer

1

This basically happens because las variables están declaradas en el ámbito del while , that is to say out of this no se puede acceder a ellas , that is why you can not access to make the respective printing.

One solution would be to declare the variables at the method level in the following way

public void tiempo(){
   /* Declaración de las variables a Nivel de método*/
   int hora1,minutos1,segundos1;
   /* resto de código */
    while (true) {...
       hora1 = Integer.parseInt(hora);/* Asigna el valor a la variable*/
       /* ... */
    } 
    while (true) {...
       minuto1 = Integer.parseInt(minutos);/* Asigna el valor a la variable*/
       /* ... */
    }  

     while (true) {...
       segundos1= Integer.parseInt(segundos);/* Asigna el valor a la variable*/
       /* ... */
    }
   /* Fuera de los While , se podrá acceder a las variables*/
  JOptionPane.showMessageDialog(null,"La hora es:"+hora1
           +"con"+minutos1+ "minutos con "+segundos1+" segundos");    
}
    
answered by 28.05.2017 / 06:36
source