我在javascript中有这个代码。
symbol = window.prompt( "Enter the symbol", "+" );
if (symbol == "+")
{
result = value1 + value2;
document.writeln( "<h1>The sum is " + sum + "</h1>" );
}
else if (symbol == "-")
{
result = value1 - value2;
document.writeln( "<h1>The sub is " + sum + "</h1>" );
}
else if (symbol == "*")
{
result = value1 * value2;
document.writeln( "<h1>The multiplication is " + sum + "</h1>" );
}
else if (symbol == "/")
{
result = value1 / value2;
document.writeln( "<h1>The division is " + sum + "</h1>" );
}
我想用Java转换它。 用户已输入两个数字,现在他必须输入4个符号(+, - ,*,/)中的一个,以便进行额外的算术运算并得到结果。
答案 0 :(得分:3)
您可以使用JOptionPane.showInputDialog(...)
来模拟window.prompt()
。其余的很简单。
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class DemoJOptionPane {
public static void main(String[] args) {
double value1 = 5, value2 = 3, result;
JDialog.setDefaultLookAndFeelDecorated(true);
String symbol = JOptionPane.showInputDialog(null, "+-*/",
"Enter the symbol", JOptionPane.OK_OPTION);
if (symbol.equals("+")) {
result = value1 + value2;
System.out.println("<h1>The sum is " + result + "</h1>");
} else if (symbol.equals("-")) {
result = value1 - value2;
System.out.println("<h1>The sub is " + result + "</h1>");
} else if (symbol.equals("*")) {
result = value1 * value2;
System.out.println("<h1>The multiplication is " + result + "</h1>");
} else if (symbol.equals("/")) {
result = value1 / value2;
System.out.println("<h1>The division is " + result + "</h1>");
}
}
}
在您的场景中可能更简单,如果您只是希望用户键入信息,您也可以直接在控制台中请求输入。
下面的示例代码将在控制台中请求输入,其行为与前一代码相同。
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
double value1 = 5, value2 = 3, result;
Scanner in = new Scanner(System.in);
System.out.print("Enter the symbol (+-*/): ");
String symbol = in.next().substring(0, 1);
in.close();
if (symbol.equals("+")) {
result = value1 + value2;
System.out.println("<h1>The sum is " + result + "</h1>");
} else if (symbol.equals("-")) {
result = value1 - value2;
System.out.println("<h1>The sub is " + result + "</h1>");
} else if (symbol.equals("*")) {
result = value1 * value2;
System.out.println("<h1>The multiplication is " + result + "</h1>");
} else if (symbol.equals("/")) {
result = value1 / value2;
System.out.println("<h1>The division is " + result + "</h1>");
}
}
}