Вопрос

I have a problem figuring out how to pad the strings printed from my array values. I thought I had a good way to do it, but it doesn't read x.length correctly so I'm curious to alternative methods or even an explanation to the bug.

import java.util.Scanner;
//================================================================
public class Array {
//----------------------------------------------------------------
    private static Scanner Keyboard = new Scanner(System.in);

    public static void main(String[] args) {
    //----------------------------------------------------------------
        char group, rLetter,letter;
        String choice ;
        String str = " ";
        double sum     =  0;
        int num     = 10; // for test
        int rows    = 10;
        int columns =  8;
        double average = 0;
        int S;
        int diff = 0;
        int totalChar=0;
        int minLen = 20;
        String x= "";

        // creating 2d array


        System.out.print("Please enter number of rows               : ");
        rows = Keyboard.nextInt();
        Keyboard.nextLine();


        double[][] figures = new double[rows][num];

        for(int t = 0; t < rows; t++) { 
            rLetter = (char)((t)+'A');
            System.out.print("Please enter number of positions in row " + rLetter + " : "); 
                columns = Keyboard.nextInt(); 
                Keyboard.nextLine(); 

            figures[t] = new double[columns]; 
        }

        // filling the array
        for(int row = 0; row < figures.length; ++row) {
            for(int col = 0; col < figures[row].length; ++col) {
                figures[row][col] = 0.0;
            }
        }

        // printing the array
        for(int row=0; row<figures.length; ++row) {
            // printing data row
            group = (char)((row)+(int)'A');
            System.out.print(group+" : ");
            for(int col=0; col<figures[row].length; ++col) {
                sum += figures[row][col];
                average = sum/figures[row].length;

                x = "   "+figures[row][col];
                diff = minLen - x.length();
                System.out.printf("%1$" + diff + "s", x);

                System.out.print(" ");

            }
            System.out.print("["+average+"]");
            System.out.println();


}
}
}

I want to produce a table that looks like this:

A:   0.0   0.0   0.0                        -        [    0.0,     0.0]

B:   0.0   0.0   0.0   0.0                    -      [    0.0,     0.0]

C:   0.0   0.0   0.0   0.0   0.0           -         [    0.0,     0.0]

Where the - is where I want to fill with space until an arbitrary length. In other words I want my print array section to be able to print each line and add spaces up to a point. Is it possible to make a method for that? I'm not to familiar with all the java methods yet so any help is appreciated. If this is a repeated question, I would appreciate a redirection to the original and I'll try to delete this one. Also sorry for the inconvenience in that case.

Это было полезно?

Решение

I am assuming you know how to build the string on the left and on the right, using StringBuilder or String concatenation.

Once you have your strings built, you can use printf as below to pad the output on the right to as many whitespace characters as you desire. In the sample code below, I have used 20 as the number of characters to pad to.

public class Pad {
    public static void main(String[] args) {
        String a = "0.0 0.0 0.0 ";
        String b = "0.0 0.0 0.0 0.0";
        String c = "[ 0.0, 0.0]";
        System.out.printf("%-20s %s\n", a, c);
        System.out.printf("%-20s %s\n", b, c);
    }
}

You can use this idea in your code above by replacing your last loop with:

    // printing the array
    for(int row=0; row<figures.length; ++row) {
        // printing data row
        StringBuilder sb = new StringBuilder();

        group = (char)((row)+(int)'A');
        sb.append(group+" : ");
        for(int col=0; col<figures[row].length; ++col) {
            sum += figures[row][col];
            average = sum/figures[row].length;

            x = "   "+figures[row][col];
            diff = minLen - x.length();
            sb.append(String.format("%1$" + diff + "s", x));

            sb.append(" ");

        }
        System.out.printf("%-75s[%f]\n", sb.toString(), average);
    }

Другие советы

You need find the maximum number of column size and iterate in each row upto max column, and place the value if the length is less than actual row length and else blank spaces. It will solve the issue.

I have added the changed code :

public class Array {

    // String result = String.format("The format method is           %s!", "great");
    //  System.out.println(result);
    //----------------------------------------------------------------
    private static Scanner Keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        //----------------------------------------------------------------
        char group, rLetter, letter;
        String choice;
        String str = " ";
        double sum = 0;
        int num = 10; // for test
        int rows = 10;
        int columns = 8;
        double average = 0;
        int S;
        int diff = 0;
        int totalChar = 0;
        int minLen = 20;
        String x = "";

        // creating 2d array


        System.out.print("Please enter number of rows               : ");
        rows = Keyboard.nextInt();
        Keyboard.nextLine();


        double[][] figures = new double[rows][num];
        int maxSize = 0;
        for (int t = 0; t < rows; t++) {
            rLetter = (char) ((t) + 'A');
            System.out.print("Please enter number of positions in row " + rLetter + " : ");
            columns = Keyboard.nextInt();
            Keyboard.nextLine();
            if (columns > maxSize) {
                maxSize = columns;
            }
            figures[t] = new double[columns];
        }

        // filling the array
        for (int row = 0; row < figures.length; ++row) {
            for (int col = 0; col < figures[row].length; ++col) {
                figures[row][col] = 0.0;
            }
        }

        // printing the array
        for (int row = 0; row < figures.length; ++row) {
            // printing data row



            group = (char) ((row) + (int) 'A');
            System.out.print(group + " : ");
            for (int col = 0; col < maxSize; ++col) {
                if (col < figures[row].length) {
                    sum += figures[row][col];
                    average = sum / figures[row].length;

                    x = "   " + figures[row][col];
                    diff = minLen - x.length();
                    System.out.printf("%1$" + diff + "s", x);

                    System.out.print(" ");
                } else {
                    System.out.print("               ");
                }
            }

            System.out.print("[" + average + "]");
            System.out.println();


        }
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top