The purpose of the program is to get two user inputs for a fraction, receive a operator from the user, and then to get two more user inputs for a second fraction. The program must check that the numbers used in both fractions range between 0-99 and have a non-zero denominator. The program also has to make sure that the user inputs a valid operator (-,+,*,/).
UPDATE: The only problem I am facing now is that none of my variables are being initialized and that I don't know how to make the output look like so:
1 1 3
--- + --- = ---
8 4 8
This is the code I have so far, I am a beginner in programming and any help would be much appreciated:
import java.util.Scanner;
public class FractionCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n1;
int n2;
int d1;
int d2;
int n;
int d;
char o;
int m1,m2;
int tempN1, tempN2;
int lcm, x;
System.out.println("Enter a numerator for fraction 1: ");
n1 = in.nextInt();
System.out.println("Enter a denominator for fraction 1: ");
d1 = in.nextInt();
if (d1 > 0) {
System.out.println();
} else {
System.out.println("Invalid denominator");
System.exit(0);
}
System.out.println("Enter an operator: ");
o = in.next().toCharArray()[0];
System.out.println("Enter a numerator for fraction 2: ");
n2 = in.nextInt();
System.out.println("Enter a denominator for fraction 2: ");
d2 = in.nextInt();
if (d2 > 0) {
System.out.println();
} else {
System.out.println("Invalid denominator");
System.exit(0);
}
switch(o){
case '*':
n = n1 * n2;
d = d1 * d2;
break;
case '/':
n = n1 * d2;
d = n2 * d1;
break;
case '+':
int max=n1>d1?n1:d1;
int min=n1<d1?n1:d1;
for(int i=1;i<=min;i++)
x=max*i;
if (x%min==0)
lcm=x;
tempN1=n1*m1;
tempN2=n2*m2;
m1=lcm/d1;
m2=lcm/d2;
n = tempN1 + tempN2;
d = lcm;
break;
case '-':
n = tempN1 - tempN2;
d = lcm;
break;
default:
System.out.println("Illegal Operator: "+ o);
break; }
}
}