我想在分數之間做一個計算器,並且如果用戶輸入+, - ,*或/它將對應於該情況。這是我的代碼至今:輸入一個特殊字符,然後在開關櫃中使用
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
您遇到的問題是什麼?錯誤的輸出?錯誤信息?請分享。 – rgettman
特別是,這裏沒有實際*問題*的跡象...... –
您的交換機很好,@AJ。指出了一個邏輯錯誤,但是你有一個更大的問題,那就是輸出一個你需要做的分數[fraction arithmetic](http://www.sheboygan.uwc.edu/developmental-math/BAW/three/lesson03熱媒)。你可以用double來完成計算,所以你不會以0結束,但會得到一個十進制數。 – Radiodef