Search code examples
javafractions

Designing a Java class to present fractions correctly


I have created a Fraction Class that does various things such as the addition, multiplication, division, subtraction, greatest common denominator, etc...

There is one part that I am lost on.

I need to make a method that returns a String version of the numerator over the denominator using hyphens to separate them and I need the hyphens to equal the length of the denominator and the numerator to be centered.

For example:

the fraction 3/4 would be 3 with a hyphen under it and the 4 under the hyphen

and something like 5/50000 would be a 5 centered above the 3rd out of 5 hyphens and then the 50000 under the hyphens.

To calculate the number of hyphens that I need, I have come up with:

int hyphenLength = String.valueOf(this.denominator).length();

So far the only thing that I have thought of doing is running a for loop in the String but I am not sure how to do this.


Solution

  • If you are just asking "how to create n-number of hyphens base on an int value", here is some ways you may look into:

    There is no direct way in Java to do. You have some way to do, the easiest way is as you said, by a for loop:

    for (int i = 0; i < hyphenLength; ++i) {
      resultStringBuilder.append('-');
    }
    

    Another way is to make use of Arrays.fill():

    char[] hyphenArray = new char[hyphenLength];
    Arrays.fill(hyphenArray, '-');
    String resultString = new String(hyphenArray);
    

    If you can make use of Apache Commons Langs, you can use StringUtils.leftPad() or rightPad():

    String resultString = StringUtils.leftPad("myData", hyphenLength, '-');