我正在尝试用Java创建一个分数计算器,它包含整数,混合分数,不正确分数和负分数。我现在唯一可以使用的是乘法,加法,减法和除以简单分数。我需要能够减少它们。到目前为止,这是我的代码。
import java.util.Scanner;
import java.lang.*;
public class Project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter an expression or quit"); //asks user
String num1 = input.next();
String operation = input.next();
String num2 = input.next();
String nume1 = num1.substring(0,1); //first numerator
int newNume1 = Integer.parseInt(nume1); //convert to int
String deno1 = num1.substring(2,3); //first denominator
int newDeno1 = Integer.parseInt(deno1); //convert to int
String nume2 = num2.substring(0,1); //second numerator
int newNume2 = Integer.parseInt(nume2); //convert to int
String deno2 = num2.substring(2,3); //second denominator
int newDeno2 = Integer.parseInt(deno2); //convert to int
if(num1.equals("quit")){
System.out.println("Goodbye!");
}
else{
//prints fraction
System.out.println("Fraction 1: " + num1);
System.out.println("Operation: " + operation);
System.out.println("Fraction 2: " + num2);
System.out.println("Numerator 1: " + newNume1);
System.out.println("Denominator 1: " + newDeno1);
System.out.println("Numerator 2: " + newNume2);
System.out.println("Denominator 2: " + newDeno2);
}
if(operation.equals("+")){
//adds numerators if denominators are the same
if(newDeno1 == newDeno2){
System.out.println("Answer is " + (newNume1 + newNume2) + "/" + + newDeno2);
}
else{
int newDenom = newDeno1 * newDeno2;
int multiplyNume = newNume1 * newDeno2;
int multiplyNume2 = newNume2 * newDeno1;
int finalNume = multiplyNume + multiplyNume2;
System.out.println("Answer is " + finalNume + "/" + newDenom);
}
}
if(operation.equals("-")){
//subtracts numerators if denominators are the same
if(newDeno1 == newDeno2){
System.out.println("Answer is " + (newNume1 - newNume2) + "/" + + newDeno2);
}
else{
int newDenom = newDeno1 * newDeno2;
int multiplyNume = newNume1 * newDeno2;
int multiplyNume2 = newNume2 * newDeno1;
int finalNume = multiplyNume - multiplyNume2;
System.out.println("Answer is " + finalNume + "/" + newDenom);
}
}
if(operation.equals("*")){
//multiplies numerators and denominators
System.out.println("Answer is: " + newNume1 * newNume2 + "/" + newDeno1 * newDeno2);
}
if(operation.equals("/")){
System.out.println("Answer is: " + newNume1 * newDeno2 + "/" + newDeno1 * newNume2);
}
}
}