Search code examples
javaarraysmathfractions

How do I format my output when computing with arrays?


I'm writing a program that will ask the user to input the numerator and denominator of two fractions and asks for which math method to use like this:

System.out.printf("Numerator for the first fraction: ");
f1 [0] = input.nextInt();
System.out.printf("Denominator for the first fraction: ");
f1[1] = input.nextInt();
System.out.printf("Numerator for the second fraction: ");
f2[0] = input.nextInt();
System.out.printf("Denominator for the second fraction: ");
f2[1] = input.nextInt();
System.out.printf("Enter the operation (+, -, *, /): ");
op = input.next();

Assuming I wanted to add the fractions I just entered,the program stores the values in an array and passes it to this method

public static int[] addFractions(int[] f1, int[] f2) {
    int[] result = new int[2];
    result[0] = (f1[0] * f2[1]) + (f2[0] * f1[1]);
    result[1] = f1[1] * f2[1];

    return simplifyFraction(result); //simplifyFraction is just a method that simplifies the numbers using gcd
}  

Here is what I use to print the answer.

addFractions(f1,f2);
        System.out.printf("%d/%d %s %d/%d = %s",f1[0],f1[1],op,f2[0],f2[1],Arrays.toString(addFractions(f1,f2)));

My answer, however, looks like this:

1/2 + 1/2 = [1, 1]

What am I doing wrong? I want my output to be displayed as just "1/1". I can handle the rest of the logic to just output the numerator if the denominator is 1, I just can't format it correctly.


Solution

  • Just do as below

    Solution 1

    int[] answer = addFractions(f1,f2);
    System.out.printf("%d/%d %s %d/%d = %d/%d", f1[0], f1[1], op, f2[0], f2[1], answer[0], answer[1]));
    

    It uses the same idea that you used to print the operands.

    Solution 2 (better than solution 1)

    Alternatively, you can use a custom formatter.

    public String formatFraction(int[] fraction){
      String result;
      if(fraction[1] == 1){
        result = String.valueOf(fraction[0]);
      }else{
        result = fraction[0] + "/" + fraction[1];
      }
      return result;
    } 
    

    and call it on the print method

    System.out.printf("%d/%d %s %d/%d = %s", f1[0], f1[1], op, f2[0], f2[1], formatFraction(formatFraction));
    

    The [ and ] are printed because it is printing an array, so it prints every element of it inside [ ] separated by a ,.