我一直在尝试在Java中创建一个简单的计算器,并且我已经成功地使程序能够用两个操作数方程(+, - ,*,/和^)工作。然而,我想知道如何才能做一个操作数的数学问题 - 绝对值(使用符号“|”),平方根(使用符号'v'),四舍五入到最接近的整数(使用符号' 〜'),sin(s),cos(c)和正切(t)。如何用Java计算器进行一个操作数的计算?
我试图绝对值操作数中可以看出:
if (operator == '|') {
answer = Math.abs(numA);
}
// In the main class
和:
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
// In the maths class
,如果你的价值观,例如像这样输入验证码只能:-3 | -3
(注:我注意到它只是第一个执行绝对值操作的数字,第二个数字可以是任何你想要的(如果你输入了-3 | -4
,你的答案仍然是3
),只要它是,确实是一个数字。
任何帮助解决这个问题,并帮助搞清楚其他单操作数的操作将不胜感激!
在此先感谢!
我的程序的源代码如下:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")){
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b')");
System.out.println("Subtraction: '-' (Ex: 'a - b')");
System.out.println("Multiplication: '*' (Ex: 'a * b') ");
System.out.println("Division: '/' (Ex: 'a/b')");
System.out.println("Exponents: '^' (Ex: 'a^b')");
System.out.println(" ");
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA, numB;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
String s=input.next();
if(s.equals("quit")){
System.out.println("Thank you for using my program!");
System.exit(0);
}
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
}
class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}
不做'麻木= input.nextDouble()',除非操作员需要它。 – Thilo 2014-10-22 04:50:00
@Thilo谢谢!我会怎么做呢? – 2014-10-22 04:55:39
不是非常优雅,但你可以将这一行移动到每个'if(operator =='块需要它。 – Thilo 2014-10-22 04:56:36