我正在尝试在分数之间创建一个计算器,如果用户输入+, - ,*或/它将在该情况下对应。这是我到目前为止的代码:
import java.util.Scanner;
public class calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String x,y;
System.out.println("Enter first fraction in a / b form: ");
x = input.nextLine();
System.out.println("Enter operation: ");
char z = input.next().charAt(0);
System.out.println("Enter second fraction in c / d form: ");
y = input.nextLine();
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
int a = Integer.parseInt(aString);
int b = Integer.parseInt(bString);
int c = Integer.parseInt(cString);
int d = Integer.parseInt(dString);
int answer = 0;
switch (z)
{
case '+':
answer = (a/b) + (c/d);
break;
case '-':
answer = (a/b) - (c/d);
break;
case '*':
answer = (a/b) * (c/d);
break;
case '/':
answer = (a/b) /(c/d);
break;
default:
System.out.println("ERROR");
break;
}
System.out.println("Answer = " + answer);
}
}
输出应该
Enter first fraction in a / b form:
1 / 2
Enter operation:
+
Enter second fraction in c / d form:
2 / 5
answer = 9/10
答案 0 :(得分:1)
问题出在这里
String aString = x.substring(0,1);
String bString = x.substring(4,5);
String cString = x.substring(0,1);
String dString = x.substring(4,5);
a=c
和b=d
这两行
String cString = x.substring(0,1);
String dString = x.substring(4,5);
应该是
String cString = y.substring(0,1);
String dString = y.substring(4,5);
在switch
打印a
b
c
d
z
的值之前,您将了解自己的正确性。
还有一件事是,您正在对int
个变量进行划分,因此结果只会在int
中。
我建议您将a
b
c
d
和answer
的类型更改为double
并使用Double.parseDouble()
将string
转换为double
。
答案 1 :(得分:0)
这个问题非常适合OOP,一个额外的类:
public class Q {
public final int numerator;
public final int denominator;
public static Q valueOf(String representation) {
Pattern pattern = Pattern.compile("([-]?\\d+) *[/:] *([-]?\\d+)");
Matcher matcher = pattern.matcher(representation.trim());
if (!matcher.matches()) {
throw new IllegalArgumentException(
"Not a quotient (like '3/4'): " + representation);
}
int num = Integer.parseInt(matcher.group(1));
int den = Integer.parseInt(matcher.group(2));
return new Q(num, den);
}
public Q(int num, int den) {
if (den < 0) {
den = -den;
num = -num;
}
int c = gcd(Math.abs(den), Math.abs(num));
denominator = den / c;
numerator = num / c;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
public Q add(Q rhs) {
int c = gcd(denominator, rhs.denominator);
int den = (denominator / c) * rhs.denominator;
int num = numerator * (rhs.denominator / c)
+ rhs.numerator * (denominator / c);
return new Q(num, den);
}
public Q mult(Q rhs) {
int den = denominator * rhs.denominator;
int num = numerator * rhs.numerator;
return new Q(num, den);
}
public static int gcd(int x, int y) {
assert x >= 0 && y >= 0;
while (x != y) {
if (x > y) {
x -= y;
} else {
y -= x;
}
}
return x;
}
}
使用这个类,几个有问题的小代码部分就会消失。