0

How can I apply string.format and printf to my output so that I can align it as per my assignment requirement?

I have 3 inputs to my method, 2 of which are char arrays which hold the two numbers, and an int array which holds their sum.

I have formatted the numbers and sum so that it is a string with appropriate commas interspersed. My task is to now align these outputs so that they always align themselves properly. The problem is I can't just set the column width to a specific number seeing as the inputs vary due to user input.

Ex: User inputs number1 and number2 (up to a max value of 30 digits), the program sums up the numbers and returns the total.

This is my code and current output:

import java.util.Scanner;
import java.util.Arrays;
public class Lab8{
    public static void main(String[] args){
        char[] num1 = {'9','2','3','8','7','4','8','6','7','2','9'};
        char[] num2 = {'3','9','9','8','3','9','2','8','3','4','9','4','5','8'};
        //getNumber("First Number: ");
        //getNumber("Second Number: ");
        //printArray(num1);
        //System.out.println();
        //printArray(num2);
        int[] finalTotal = sumArrays(num1,num2);
        //sumArrays(num1, num2);

        printOutput(num1, num2, finalTotal);

    }
    //-------- 
   /** Read a line of message from keyboard and return it as an array of char
      @return: Array of characters 
     */
    public static char[] getNumber(String msg){
        String myMessage;
        System.out.print(msg);
        Scanner input = new Scanner(System.in);
        myMessage = input.nextLine();// Read a line of message
        return myMessage.toCharArray();
   }   


   public static int[] sumArrays(char[] num1, char[] num2){

        int sum= 0, carry = 0, size = 0, min = 0;

        if(num1.length > num2.length){
            size = num1.length + 1;
            min = num2.length;
        }else{
            size = num2.length + 1;
            min = num1.length;
        }   

        int[] sumArray = new int[size];


        int i = num1.length-1;
        int j = num2.length-1;
        int k = size-1;

        while(i >= 0 && j >=0){

           sum = Character.getNumericValue(num1[i]) + Character.getNumericValue(num2[j]) + carry;
           i--;
           j--;
           sumArray[k] = sum % 10;
           sum = sum / 10;
           carry = sum % 10;
           k--;

       }   

        while(i >= 0){

            sum = Character.getNumericValue(num1[i]) + carry;
            sumArray[k] = sum % 10;
            sum = sum / 10;
            carry = sum % 10;
            i--;
            k--;

        }

        while( j >= 0){

            sum = Character.getNumericValue(num2[j]) + carry;
            sumArray[k] = sum % 10;
            sum = sum / 10;
            carry = sum % 10;
            j--;
            k--;

        }   

        sumArray[k] = carry;

        int[] finalSum = new int[sumArray.length-1];

        finalSum = printArray(sumArray);

        return finalSum;

   }  

      public static void printOutput(char[] num1, char[] num2, int[] sum){

        char[] largest = new char[1];
        char[] smallest = new char[1];
        char[] tmp = new char[1];

        if(num2.length > num1.length){
            largest = num2;
            smallest = num1;
        }else{
            largest = num1;
            smallest = num2;
        }     

        String number1 = formatString(largest);
        String number2 = formatString(smallest);
        String total = formatString(sum);


        System.out.printf("%s%n", number1 + " +");

        for(int i = 0; i < (number1.length() -  number2.length()); i++){
            System.out.print(" ");
        }   
        System.out.printf("%s%n%s%n%s", number2, totalLine(sum),total);

   }  


   public static String formatString(char[] num){

       String formattedString = "";

       for(int i = 0; i < num.length; i++){

           if(i == 0){
                formattedString = num[num.length-1-i] + formattedString;
                continue;
            }

            if(i % 3 == 0){
                formattedString = "," + formattedString;
            }

            formattedString = num[num.length-1-i] + formattedString;
       }   

       return formattedString;

   }  


    public static String totalLine(int[] num){

        String totalLine = "";

        for(int i = 0; i < num.length; i++){

            totalLine = "- " + totalLine;

        }   

        return totalLine;

    }   


    public static String formatString(int[] num){

        String formattedString = "";

       for(int i = 0; i < num.length; i++){

           if(i == 0){
                formattedString = num[num.length-1-i] + formattedString;
                continue;
            }

            if(i % 3 == 0){
                formattedString = "," + formattedString;
            }

            formattedString = num[num.length-1-i] + formattedString;
       }   

       return formattedString;

   }  


   public static int[] printArray(int[] arr){
        int[] sum = new int[arr.length-1];
        if(arr[0] == 0){
           for(int i = 1; i < arr.length; i++){
                sum[i-1] = arr[i];
            }
        }else{
            for(int i = 0; i < arr.length; i++){
                sum[i] = arr[i];
            }   
        }   
        return sum;
    }

}

OUTPUT(wrong)

39,983,928,349,458 +
92,387,486,729
- - - - - - - - - - - - - - 
40,076,315,836,187

OUTPUT(correct way)

       39,983,928,349,458 + 
           92,387,486,729
     --------------------
       40,076,315,836,187

As you can see, my formatting is flawed. I'm totally unsure how to properly format this output so that it displays correctly every time even with differing number values. It should be formatted with the larger number above the smaller number and then a total line followed by the sum.

tgtony
  • 11
  • 4
  • 1
    Did you look at the docs for `printf` and its format specifiers? Even a trivial search for right-justifying Java printf seems like a good start, e.g., I found this: https://stackoverflow.com/questions/15961130/align-printf-output-in-java – Dave Newton Jul 06 '18 at 21:09
  • I looked at this one before but I fail to see how it can help me. Maybe I'm not thinking hard enough about this . – tgtony Jul 06 '18 at 21:13
  • Hm. The accepted answer has string formatting with a width; perhaps I misunderstood. Or perhaps you didn't read enough and try anything. shrug. In any case, I'm pretty sure you can right-justify Java strings, and that searching for just that will lead you to an answer. – Dave Newton Jul 06 '18 at 21:16
  • You can try inserting spaces in start of smallest. Number of spaces to be added = largest.length-smallest,length – Punit Mittal Jul 06 '18 at 21:18
  • Can you paste the complete code here. (formatString and totalLine methods and how are you calling printOutput with calculated sum. – Deepak Agrawal Jul 06 '18 at 21:26
  • Just tried doing that and it's close but still off – tgtony Jul 06 '18 at 21:26
  • Then the math is wrong; that's all the built-in formatting stuff does--checks the length and pads. – Dave Newton Jul 06 '18 at 21:28
  • @DeepakAgrawal I have gone ahead and done that. – tgtony Jul 06 '18 at 21:33

3 Answers3

1

So after reading some more I realized what I was trying to achieve didn't necessarily require string formatting or printf statements. I ended up, like the previous comments and answer above suggested, just formatting the output with multiple print statements. It's definitely not the most beautiful code to look at but it gives me the exact output I was after.

This was the code that did the trick:

System.out.println("  " + number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
    System.out.print(" ");
}
System.out.println("  " + number2);
System.out.print(" ");
for(int j = 0; j < ((number1.length() - number2.length())+ number2.length()+1); j++){
    System.out.print("-");
}
System.out.println();
System.out.print("  " + total);
tgtony
  • 11
  • 4
  • Or you could just build your format string based on lengths, e.g., "%20s" space-pads and right-justifies, so you'd take your first number, append the " +", take your second number and append equivalent spaces, and build the appropriate format string. YMMV. Under the hood it's all the same operations. – Dave Newton Jul 07 '18 at 11:27
0

Based on your comments, it seems like the math is tripping you up. Let me see if I can help.

(You implied this was homework, so I'm not going to literally give you the code, but this should set you on the right path. I'm sure you can implement it yourself.)

The number of digits in a number is:

Math.floor(Math.log10(x)) + 1

(See this conversation for a proof.)

Use that to find the length of the answer. (This is always going to be the longest number or tied for the longest, since you're adding numbers together.) Make your line of ---s this long.

Append to the front of each line length of that line - length of the answer number of spaces.

(If you want to have a certain number of spaces as an indent on the whole problem, as you have in your example, then append length of line - length of answer + indent number of spaces to the front of each line instead.)

Append + (space and a plus) to the end of the first line, and (two spaces) to the other lines.

That should work!

Hazel
  • 18
  • 4
0

You can use ArrayLists instead of char arrays to simplify math. But you have to adjust the code a bit. Here is the procedure.

  • Get two lines of inputs in to two array lists using getNumber() method. (let's call the B and C)
  • Take the sum to a third array list using the sum method.(Let's call A)
  • Find the sizes of array lists using size() method in arraylist.
  • Compare the sizes and get the difference between biggest array list and other two array lists seperately.(Largest would be A so get A-B and A-C). And store sizes B and C sizes for future use in two variables.
  • Add (A-B) number of whitespaces(" ") into B arraylist staring from 0 index using add(index,object) method in array list.(in add(index,object) method shifts the element currently at that position (if any) and any subsequent elements to the right)
  • Do the Same for the C array list as well as well.
  • Find the Array List highest value from B and C using the previously stored sizes and append that array list in to the formatted string first.(using a loop)
  • Then after "+" and "\n", append the second array list to the format string.

  • Finally append the array list containing sum(A) into the format string.

  • As we added whitespaces to make all arrays the same size, the formatted string should be well formated.
Nipun Thennakoon
  • 3,586
  • 1
  • 18
  • 26