¿Podría alguien darme una pista de por qué esta prueba y captura no funciona? Lanza una excepción de escáner en lugar de imprimir el mensaje que espero.Probar/atrapar en Java
import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Boolean test = true;
while (test == true) {
try {
double x, y;
String operator;
Scanner scan = new Scanner(System.in);
Scanner scan_2 = new Scanner(System.in);
Scanner ScanOperator = new Scanner(System.in);
System.out.println(" Enter a double value: ");
x = scan.nextDouble();
System.out.println(" Enter another double value: ");
y = scan_2.nextDouble();
System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
operator = ScanOperator.nextLine();
if (operator.equals("x") || operator.equals("X")) {
test = false;
System.out.println("No calculation was made!!!");
}
System.out.println(Calculation(operator, x, y));
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
}
}
public static double Calculation(String operator, double x, double y) {
double result = 0;
double myAdd = 0;
double mySub = 0;
double myMult = 0;
double myDiv = 0;
double myPower = 0;
double myMod = 0;
if (operator.equals("+")) {
myAdd = x + y;
result = myAdd;
} else if (operator.equals("-")) {
mySub = x - y;
result = mySub;
} else if (operator.equals("*")) {
myMult = x * y;
result = myMult;
} else if (operator.equals("/")) {
myDiv = x/y;
result = myDiv;
} else if (operator.equals("^")) {
myPower = Math.pow(x, y);
result = myPower;
} else if (operator.equals("%")) {
myMod = x % y;
result = myMod;
} else {
}
return result;
}
}
¿Qué le dice la excepción? – nos
Este código está bien. Puedo ejecutarlo tal como es localmente. – Thunderhashy