Switch structure to avoid showing statements

1

I have this little code in java / I'm starting to learn /

package com.switchtuto;

import java.util.Scanner;

public class switchcase2 {


public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("menu de opciones");
    System.out.println("1: Sumar");
    System.out.println("2: Restar");
    System.out.println("3: Multiplicar");
    System.out.println("4: Dividir");
    System.out.println();
    System.out.println("ingrese su opcion");
    int opcion = scanner.nextInt();

    if(opcion>=1 && opcion<=4){
    System.out.println("Ingrese el primer numero");
    int x = scanner.nextInt();
    System.out.println("Ingrese el segundo numero");
    int y = scanner.nextInt();
    int resultado = 0;

switch (opcion) {
case 1:
resultado= x+y;
break;
case 2:
resultado = x-y;
break;
case 3:
resultado = x*y;
break;
case 4:
resultado =x/y;
break;
default:
    System.out.println("Tu Eres Loco");
    break;
}
System.out.println("Resultado:");
System.out.println(resultado);
}

}
}

and I would like the program not to show the messages to ask for a number when the case is the default, because first it asks for the numbers and then placed any number shows the warning.

Final code:

package com.paquetes;

import java.util.Scanner;

public class switchcase2 {


public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("menu de opciones");
    System.out.println("1: Sumar");
    System.out.println("2: Restar");
    System.out.println("3: Multiplicar");
    System.out.println("4: Dividir");
    System.out.println();


     int opcion=0,x=0,y=0,resultado=0;

    do
    {
     System.out.println("Ingrese Opción Válida");
     opcion = scanner.nextInt();
    }while((opcion<1) || (opcion>4)); 

    System.out.println("Ingrese el primer numero");
    x = scanner.nextInt();
    System.out.println("Ingrese el segundo numero");
    y = scanner.nextInt();

    switch (opcion) {
case 1:
resultado= x+y;
break;
case 2:
resultado = x-y;
break;
case 3:
resultado = x*y;
break;
case 4:
resultado =x/y;
break;
default:
    System.out.println("Tu Eres LOCO5");
    break;
}
System.out.println("Resultado:");
System.out.println(resultado);
}
}
    
asked by Victor Alejandro Alvarado Vilo 14.09.2016 в 05:15
source

3 answers

2

You could use the Intruction do-While (do while) to validate the entry of the option and it will not leave the loop while the option is between 1 and 4 and to prevent the program from being hung by Exceptions as NumberFormatException , add a try{ } catch(){}

 int opcion=0,x=0,y=0,resultado=0;
  do
  {
   System.out.println("Ingrese Opción Válida");
    try
    {
     opcion = Integer.parseInt(scanner.next());
    }
    catch(NumberFormatException ex){
     System.out.println("No es Número , Verificar su Entrada "+  ex.getMessage());
    }
}
while(opcion<1 || opcion >4);
    // Verifico si no está en el rango si retorna verdadero regresa al hacer
    //luego solicito números si sale del ciclo es porque tengo una opción correcta


System.out.println("Ingrese el primer numero");
 x = scanner.nextInt();
System.out.println("Ingrese el segundo numero");
 y = scanner.nextInt();


switch (opcion) {...}
System.out.println("Resultado "  + resultado);
    
answered by 14.09.2016 / 05:45
source
2

This is the solution to your problem, based on the analysis of your code.

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    System.out.println("menu de opciones");
    System.out.println("1: Sumar");
    System.out.println("2: Restar");
    System.out.println("3: Multiplicar");
    System.out.println("4: Dividir");
    System.out.println();
    System.out.println("ingrese su opcion");
    int opcion = scanner.nextInt();

    if(opcion>=1 && opcion<=4){
        System.out.println("Ingrese el primer numero");
        int x = scanner.nextInt();
        System.out.println("Ingrese el segundo numero");
        int y = scanner.nextInt();
        int resultado = 0;

        switch (opcion) {...}

        System.out.println("Resultado:" + resultado);
    }else{
        System.out.println("Tu Eres Loco");
    }
}
    
answered by 14.09.2016 в 06:22
1

If I understood your question you want that if the user puts a different number of 1,2,3, or 4 does not show the messages to ask for numbers, if so, you could put that in an if

         System.out.println("ingrese su opcion");
        int opcion = scanner.nextInt();
        //inicializo y declaro las varibles
        int x = 0, y = 0, resultado = 0;
        //si es opcion valida pido los valores por teclado
        if (opcion >= 1 && opcion <= 4) {
            System.out.println("Ingrese el primer numero");
             x = scanner.nextInt();
            System.out.println("Ingrese el segundo numero");
             y = scanner.nextInt();

        }

        switch (opcion) { //codigo que ya tienes


}
    
answered by 14.09.2016 в 05:45