Java calculator problem (conditional)

-1

I have the following code

import java.util.Scanner; 

public class Calculadora { 
  public static void main(String[] args) { 
  Scanner numero = new Scanner(System.in); 
  double numero1; 
  double numero2; 
  double suma; 

  System.out.print("primer entero"); 
  numero1 = numero.nextDouble(); 
  if((numero1 <= 0) || (numero1 >= 0)){ 
    System.out.print("segundo entero"); 
    numero2 = numero.nextDouble(); 
    if((numero2 <= 0) || (numero2 >= 0)){ 
      suma = numero1 + numero2; 
      System.out.printf("el valor es " + suma); 
    } else { 
      System.out.println("Valor invalido"); 
    } 

  } else { 
    System.out.println("Valor invalido"); 
  } 

} 

It's something basic so I'm just learning java, my question is this. how can I do so that when the user enters a value other than a numerical value, I do not get an error of "Exception in thread" main "... at java.util.Scanner.throwFor ...".

how can I implement a conditional, that when the user places something other than a numerical value, it throws "invalid value" or something like that. Thank you.

    
asked by Diego Quintero 16.10.2018 в 05:22
source

1 answer

0

my solution would be the following, as the previous user said, you should implement the try & catch the try is used for fragments of codes that are prone to fail or when there are curious users. if the program that is running inside try fails, in this case it prints "Invalid value".

import java.util.Scanner;

public class Calculadora {
public static void main(String[] args) {
    Scanner numero = new Scanner(System.in);
    double num1;
    double num2;
    double suma;
    try {
        System.out.println("Primer entero ");
        num1 = numero.nextDouble();
        System.out.println("Segundo entero");
        num2 = numero.nextDouble();
        suma = num1 + num2;
        num2 = numero.nextDouble();
        System.out.println("valor suma" + suma);
    } catch (Exception e) {
        System.out.println("Valor invalido");
    }
}

}

    
answered by 16.10.2018 в 16:37