我有问题。在课堂上,我们必须做一个简单的计算器,我的问题是我想写一个数字,然后是运算符,然后是一个数字。不知何故,我的代码无法正常工作。我可以输入第一个数字,但是程序关闭:/为什么呢?是因为我使用了数据类型字符串吗?
提前感谢大家!
这是我的代码:
import java.util.Scanner;
import java.math.*;
public class Calculatrice
{
public static void main(String args[])
{
double num1;
Scanner keyb = new Scanner(System.in);
System.out.println("Calculette Simple");
System.out.print("Valeur actuelle: ");
num1 = keyb.nextDouble();
System.out.print("Entrez un operateur: ");
String i;
i = keyb.nextLine();
double result = 0;
switch (i)
{
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result,num1);
break;
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
break;
}
keyb.close();
}
}
您需要循环:您需要从命令行读取数据,直到验证条件为止,才能读取一个以上的字符串(数字,运算符或所需的任何内容)。然后尝试这样的事情:
// your initialization of scanner
i = keyb.nextLine();
double result = 0;
while (!i.equals("end")) { // I use this as exit condition, but you can use whatever you want
switch (i) {
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result, num1);
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
}
}
// close scanner
您需要一些具有退出条件的循环(我相信输入中为'x')就像是while(!“ x” .equals(i)){切换(i)...}