2

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 (-,+,*,/).

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
--- + ---  = ---
 4     8      8

Here is the code I have so far, any help would be much appreciated because my knowledge for using java is minimal:

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; }
 }
}
Joe Eastman
  • 69
  • 2
  • 4
  • 10
  • possible duplicate of [Skipping nextLine() after use nextInt()](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) – StackFlowed Oct 08 '14 at 15:44
  • @jgr208 Homework questions are technically acceptable, so long as they follow the usual StackOverflow question guidelines. Admittedly, the wording of this question may be a bit broad, as the actual "question statement" is a little ambiguous. – Paul Richter Oct 08 '14 at 15:50
  • Note that you'll probably want to reduce the fraction in the `*` and `/` cases; 1/3 * 3/4 should be 1/4, not 3/12. (Actually, the fraction needs to be reduced for `+` and `-` also; 1/3 + 1/6 = 1/2, and computing the `lcm` isn't enough to get the result reduced.) – ajb Oct 08 '14 at 16:00
  • @wrongAnswer I'll have to disagree there; he's using `next()` and `nextInt()`, but not `nextLine()`. Without actually using `nextLine()`, you won't hit the same issue. – Dennis Meng Oct 09 '14 at 05:06

3 Answers3

0

Maybe you want to enter OOP (object oriented programming):

Q x = new Q(1, 4);
Q y = new Q(1, 8);
Q z = x.plus(y);
System.out.println("%s + %s = %s%n", x, y, z);

(1 / 4) + (1 / 8) = (3 / 8)

public class Q {
    final int numerator;
    final int denominator;

    public Q(int numerator, int denominator) {
        int g = gcd(numerator, denominator);
        this.numerator = numerator / g;
        this.denominator = denominator / g;
    }

    @Override
    public String toString() {
        return String.format("(%d / %d)", numerator, denominator);
    }

    public Q plus(Q rhs) {
        return new Q(numerator * rhs.denominator + rhs.numerator * denominator,
            denominator * rhs.denominator);
    }
Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
0

One part of the problem: You have some logic that you need to perform both for '+' and '-', but the way you've written it, it will be executed for '+' only:

switch(o){
    ... other cases
    case '+':
        ... logic to compute lcm and other things
        n = tempN1 + tempN2;
        d = lcm;
        break; 

    case '-':
        n = tempN1 - tempN2;
        d = lcm;
        break;

When the user enters '-', the program won't go into the part under case '+'. This means that tempN1, tempN2, and lcm won't be set up. If you're getting errors from the compiler about uninitialized variables, this is one reason why.

One way to write code that is executed for multiple cases:

switch(o){
    ... other cases
    case '+':
    case '-':
        ... whatever logic will apply to both cases
        if (o == '+') {
            ... whatever logic will apply to + only
        } else {
            ... whatever logic will apply to - only
        }
        ... if you have more logic for both cases, you can put it here
        break;

That is, when you have more than one case right next to each other, with no code in between, the following code applies to multiple cases. (This is because of "fall-through". It actually goes to the case '+', and then since there's no break in the case '+' code, it falls through to the case '-'. But it's not recommended to take advantage of fall-through, except when there is no code at all as in the above.)

ajb
  • 29,914
  • 3
  • 49
  • 73
0

UPDATE:

Be aware that this is my no means complete and/or the best solution, but at least it should take you in the right direction. You will still have to reduce fractions and do some other tweaks.

import java.math.BigInteger;
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 = 0;
        int d;
        char o;

        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 '+':
            case '-':

                d = gcd(d1, d2);

                n1 *= d / d1;
                n2 *= d / d2;

                if(o == '+') {
                    n = n1 + n2;
                }
                else if(o == '-') {
                    n = n1 - n2;
                }

                break;
            default:
                System.out.println("Illegal Operator: " + o);
                return;
        }

        System.out.printf(" %d     %d     %d\n", n1, n2, n);
        System.out.printf("--- %c --- = ---\n", o);
        System.out.printf(" %d     %d     %d\n", d1, d2, d);
    }

    private static int gcd(int d1, int d2) {
        BigInteger gcd = new BigInteger(String.valueOf(d1)).gcd(new BigInteger(String.valueOf(d2)));
        return gcd.intValue();
    }
}
Yoel Nunez
  • 2,078
  • 1
  • 10
  • 18
  • The reason that there are "uninitialized variable" errors is that the logic is wrong. Adding initial values papers over the problem instead of solving it. When there are uninitialized variable errors, **the first thing you need to do is check your logic**. _Then_ add an initializer if necessary. – ajb Oct 08 '14 at 16:03
  • @ajb I meant to say "You have to initialize some var...". I updated my answer explaining why I initialized them to 0. But I had mentioned that his logic wasn't right – Yoel Nunez Oct 08 '14 at 16:11
  • @ajb I'm not understanding what the right logic is, could you possible provide me with some insight on the correct logic to point me in the right direction? – Joe Eastman Oct 08 '14 at 19:38
  • @JoeEastman In your original post, it looks like you tried to write a `for` loop with three statements in the body, but you didn't use curly braces, so only the first statement will be executed multiple times. Past that, you'll need to do your own debugging. If there's something you don't understand about Java so that it looks like it should work but it doesn't, we can help with that, but we can't do all the work for you. – ajb Oct 09 '14 at 05:40