0
I’m also wanting to implement a try
/catch
within the while
so that when a user enters a double
with a dot instead of a comma, the program points the error and sends it back to code execution.
But when testing the error, the program enters a loop infinity, just putting a break
the program stops running, but wanted to know if there is a possibility to return the execution of the program without having to run it again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Teste_Calc extends Calculadora {
public static void main(String[] args) {
Calculadora c = new Calculadora();
Scanner sc1 = new Scanner(System.in);
double n1,n2;
double resultado;
int opcao;
boolean x=true;
while(x) {
try {
System.out.println("---------------------------------");
System.out.println("Escolha uma das opções a seguir:");
System.out.println("1) Somar!");
System.out.println("2) Subtrair!");
System.out.println("3) Multiplicar!");
System.out.println("4) dividir!");
System.out.println("5) Sair do programa!");
System.out.println("---------------------------------");
opcao = sc1.nextInt();
if (opcao == 5) {
System.out.println("Programa finalizado!");
break;
}
else{
switch(opcao) {
case 1:
System.out.println("Insita o valor do numero 1:");
n1 = sc1.nextDouble();
System.out.println("Insira o valor do numero 2:");
n2 = sc1.nextDouble();
resultado = c.somar(n1,n2);
System.out.println("O resultado é: "+ resultado);
break;
case 2:
System.out.println("Insita o valor do numero 1:");
n1 = sc1.nextDouble();
System.out.println("Insira o valor do numero 2:");
n2 = sc1.nextDouble();
resultado = c.subtrair(n1,n2);
System.out.println("O resultado é: "+ resultado);
break;
case 3:
System.out.println("Insita o valor do numero 1:");
n1 = sc1.nextDouble();
System.out.println("Insira o valor do numero 2:");
n2 = sc1.nextDouble();
resultado = c.Multiplicar(n1,n2);
System.out.println("O resultado é: "+ resultado);
break;
case 4:
System.out.println("Insita o valor do numero 1:");
n1 = sc1.nextDouble();
System.out.println("Insira o valor do numero 2:");
n2 = sc1.nextDouble();
resultado = c.dividir(n1,n2);
System.out.println("O resultado é: "+ resultado);
break;
default:
System.out.println("Opção invalida");
}
}
}
catch(InputMismatchException exception) {
System.out.println("Caracter inserido não compatível!" );
continue;
}
}
}
}
Try changing the value of x to false instead of setting break;
– Isaías de Lima Coelho
You are using the Try catch from the menu. You have to set the Try/catch to the code snippet that receives the input from your double.
– Evilmaax
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero