如果某个情况为真,我如何告诉我的程序忽略一条指令?



我是一个非常初级的java编码员,我正在使用swing编写一个简单的计算器,我想将平方根实现到操作符中。我希望在运算符是平方根的情况下,计算器不会要求输入第二个数字。

package swingcalculator;
import javax.swing.JOptionPane;
public class SwingCalculator {

public static void main(String[] args) {

double num1, num2, answer;
String operator;

num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first number:"));
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):"); 
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));

switch(operator) {

case "+":
answer = num1 + num2;
break;

case "-":
answer = num1 - num2;
break;

case "*":
answer = num1 * num2;
break;

case "/":
answer = num1 / num2;
break;

case "sqrt":
answer = Math.sqrt(num1);
break;

case "^":
answer = Math.pow(num1, num2);
break;

default:
System.out.println("You have entered an invalid operator");
return;

}

if (Boolean.parseBoolean(operator) == Boolean.parseBoolean("sqrt")){
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
else{
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
}
}

任何帮助将不胜感激!

operator =行之后的所有内容放在条件语句中(您也可以将JOptionPane.showMessageDialog行移动到条件语句的适当块中,因为您不需要再次检查operator):

operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):"); 
if (!operator.equals("sqrt")) { 
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch (...) { ... }
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
} else {
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):"); 
if(!operator.equals("sqrt"){
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
}      

只有当操作符不是'sqrt'时才读取第二个数字,但是您的程序似乎有许多异常,正如其他人在评论中建议的那样

相关内容

  • 没有找到相关文章

最新更新