-1
我正在使用Eclipse中的一個小型計算器,用戶在此輸入方程式如1 + 1
。但是,我不確定如何讓用戶輸入更復雜的方程式,如1 + 2 * 3/4
。在Java計算器中允許多個輸入
另外,如果用戶試圖輸入一個不是有效等式的字符串,我想要出現一個錯誤。這裏是我的代碼:
public static double addition(double x, double y) // The Addition Operation
{
double add = x + y;
return add;
}
public static double subtraction(double x, double y) // The Subtraction Operation
{
double sub = x - y;
return sub;
}
public static double division(double x, double y) // The Devision Operation
{
double div = x/y;
return div;
}
public static double multiplication(double x, double y) // The Multiplication Operation
{
double multi = x * y;
return multi;
}
public static double factorial(double x) // The Factorial (F!)
{
double result = 1;
while (x > 1)
{
result = result * x;
x = x - 1;
}
return result;
}
static Scanner scanner = new Scanner(System.in); // a Global Scanner.
public static void main(String[] args)
{
double numb1, numb2;
char operation;
System.out.println("Enter Your Equation: ");
// Split string by space
String[] parts = scanner.nextLine().split("");
// Convert to corresponding types
operation = parts[1].charAt(0);
switch (operation)
{
case '+':
numb1 = Integer.parseInt(parts[0]);
operation = parts[1].charAt(0);
numb2 = Integer.parseInt(parts[2]);
System.out.println("The Product is: " + addition(numb1, numb2));
break;
case '-':
numb1 = Integer.parseInt(parts[0]);
operation = parts[1].charAt(0);
numb2 = Integer.parseInt(parts[2]);
System.out.println("The Product is: " + subtraction(numb1, numb2));
break;
case '*':
numb1 = Integer.parseInt(parts[0]);
operation = parts[1].charAt(0);
numb2 = Integer.parseInt(parts[2]);
System.out.println("The Product is: " + multiplication(numb1, numb2));
break;
case '/':
numb1 = Integer.parseInt(parts[0]);
operation = parts[1].charAt(0);
numb2 = Integer.parseInt(parts[2]);
System.out.println("The Product is: " + division(numb1, numb2));
break;
case '!':
numb1 = Integer.parseInt(parts[0]);
operation = parts[1].charAt(0);
System.out.println("The Product is: " + factorial(numb1));
}
}
我建議使用一些正則表達式規則來分割大字符串與運營商的許多數字.. http://www.dreamincode.net/forums/topic/236807-regex-use-for-a-simple-calculator-應用/ 這可能對你有所幫助 – HackerGK
@ l19但是......但是,你會如何知道它的作用? –