I have a problem that I think any intermediate programmer can solve. The case is that I have a while loop in which if I put in the input (for example) "add" and add the numbers the subtraction is done but then the while is executed again and it comes out as if it had put nothing in the input and I get the error (and then, obviously, it runs again).
Code:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("\tCalculadora");
System.out.println("--------------------------");
int condicion = 1;
while(condicion == 1){
System.out.println("¿Qué operación desea realizar?");
System.out.println("Suma");
System.out.println("Resta");
System.out.println("Salir");
String operacion = scan.nextLine();
if(operacion.toLowerCase().equals("suma")){
System.out.println("Introduce los números que quieres sumar");
System.out.println("Número 1: ");
double numero1 = scan.nextDouble();
System.out.println("Número 2: ");
double numero2 = scan.nextDouble();
Suma suma = new Suma(numero1, numero2);
System.out.println("Resultado: " + suma.getSuma());
}else if(operacion.toLowerCase().equals("resta")){
System.out.println("Introduce los números que quieres restar");
System.out.println("Número 1: ");
double numero1 = scan.nextDouble();
System.out.println("Número 2: ");
double numero2 = scan.nextDouble();
Resta resta = new Resta(numero1, numero2);
System.out.println("Resultado: " + resta.getResta());
}else if(operacion.toLowerCase().equals("salir")){
System.out.println("¡Adiós! ;)");
condicion = 0;
}else{
System.out.println("Error: Puede ser que hayas escrito mal la palabra. Vuelve a intentarlo");
}
}
}
}
By console:
Calculadora
--------------------------
¿Qué operación desea realizar?
Suma
Resta
Salir
SUMA (input)
Introduce los números que quieres sumar
Número 1:
1 (input)
Número 2:
1 (input)
Resultado: 2.0
¿Qué operación desea realizar?
Suma
Resta
Salir
Error: Puede ser que hayas escrito mal la palabra. Vuelve a intentarlo
¿Qué operación desea realizar?
Suma
Resta
Salir
If you need the other two classes, I'll send them to you, but I do not think it's necessary, that's why I do not add them.
Greetings! ;)