user2268653
user2268653

Reputation: 1

Formatting the output of arrays, into a column

I just needed some assistance on formatting the output into a specific fashion. I satisfied all the requirements of the assignment, except the output.

I apologize for the bad format of this post, any suggestions and help is greatly appreciated.

I need the output to look like:

Mr. Random - $500
Mr. BobRandom - $250
etc-8 more times
(sum total of all dollars)

Heres my code:

import javax.swing.JOptionPane;
import java.util.Arrays;

public class PeerTutors {
    public static void main(String[] args) {
        String[] myNameArray = new String[2];
        String[] myGradeArray = new String[2];
        double[] myStudentArray = new double[2];
        double[] stipend = new double[2];
        int sum = 0;

        for (int i = 0; i < 2; i++) {
            myNameArray[i] = (JOptionPane
                    .showInputDialog(null,
                            "Enter the Peer Tutor name, last name then followed by the first name."));

        }
        Arrays.sort(myNameArray, String.CASE_INSENSITIVE_ORDER);
        JOptionPane.showMessageDialog(null, "The Peer Tutors Names are :"
                + Arrays.toString(myNameArray));

        for (int a = 0; a < 2; a++) {
            myGradeArray[a] = JOptionPane.showInputDialog(null,
                    "Please enter the highest degree earned for: "
                            + myNameArray[a]);
        }
        JOptionPane.showMessageDialog(null, "The Peer Tutors Names are :"
                + Arrays.toString(myNameArray) + Arrays.toString(myGradeArray));

        for (int b = 0; b < 2; b++) {
            myStudentArray[b] = Double.parseDouble(JOptionPane.showInputDialog(
                    null, "Please enter the number of students"
                            + myNameArray[b] + " has assisted"));
        }
        JOptionPane.showMessageDialog(null,
                "The Peer Tutors Report: " + Arrays.toString(myNameArray)
                        + "with" + Arrays.toString(myStudentArray)
                        + " of children tutoring");

        for (int c = 0; c < 2; c++) {
            if (myGradeArray[c].equals("BS")) {
                stipend[c] = 9.5 * myStudentArray[c];

            } else if (myGradeArray[c].equals("MS")) {
                stipend[c] = 15 * myStudentArray[c];

            } else {
                stipend[c] = 20 * myStudentArray[c];
            }
        }
        for (double d : stipend) {
            sum += d;
        }

        for (int d = 0; d < 2; d++) {
            JOptionPane.showMessageDialog(null, myNameArray[d] + "-"
                    + stipend[d] + "\n");

        }
    }
}

Upvotes: 0

Views: 4035

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347184

Basically, for each column, you need some kind of list (either an array or preferably an List). You also need to maintain information on each columns max-width (I typically put this in another List).

You need to loop each line, breaking to down into it's column elements and place each element in the corresponding column List. You should also be calculating the width requirements for each column as you go.

Once you have this all structured out, you need to then reconstruct the out put, using something like a StringBuilder to rebuild each line of the output but so that each column has the required additional spacing to allow the columns to flow.

Updated with example

Now, normally, I would store each row as an individual object, as it makes it easier to maintain a consistent idea of the total number of rows, but, using you code as a jumping off point...

import java.text.NumberFormat;

public class TestTextColumnFormatting {

    public static void main(String[] args) {
        String[] myNameArray = new String[]{
            "Mr. Samete",
            "Ms. Torbura",
            "Mr. Perem",
            "Mr. Rothaw",
            "Miss. Endemos",
            "Mr. Chomoshon",
            "Mrs. Aldir",};
        double[] stipends = new double[]{
            500,
            200,
            300,
            1000,
            250,
            125,
            600,
            338
        };
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        double tally = 0;

        int columnWidths[] = new int[2];
        for (int index = 0; index < myNameArray.length; index++) {
            columnWidths[0] = Math.max(columnWidths[0], myNameArray[index].length());
            columnWidths[1] = Math.max(columnWidths[1], nf.format(stipends[index]).length());
            tally += stipends[index];
        }

        columnWidths[1] = Math.max(columnWidths[1], nf.format(tally).length());

        StringBuilder sb = new StringBuilder(128);
        for (int index = 0; index < myNameArray.length; index++) {

            String name = myNameArray[index];
            String stipend = nf.format(stipends[index]);

            sb.append(name).append(fill(name, columnWidths[0], ' ')).append(" ");
            sb.append(fill(stipend, columnWidths[1], ' ')).append(stipend);
            sb.append("\n");

        }


        sb.append(fill("", columnWidths[0], ' ')).append(" ");
        sb.append(fill("", columnWidths[1], '=')).append("\n");
        sb.append(fill("", columnWidths[0], ' ')).append(" ");
        sb.append(fill(nf.format(tally), columnWidths[1], ' ')).append(nf.format(tally));
        sb.append("\n");

        System.out.println(sb.toString());

    }

    public static String fill(String sValue, int iMinLength, char with) {

        StringBuilder filled = new StringBuilder(iMinLength);

        while (filled.length() < iMinLength - sValue.length()) {

            filled.append(with);

        }

        return filled.toString();

    }
}

This will then output something like...

Mr. Samete      $500.00
Ms. Torbura     $200.00
Mr. Perem       $300.00
Mr. Rothaw    $1,000.00
Miss. Endemos   $250.00
Mr. Chomoshon   $125.00
Mrs. Aldir      $600.00
              =========
              $2,975.00

Updated

I'm such an idiot, I just realised that you're using a JOptionPane :P

The simplest solution would be to construct a HTML table and let Swing render it for you...

enter image description here

import java.text.NumberFormat;
import javax.swing.JOptionPane;

public class TestTextColumnFormatting {

    public static void main(String[] args) {
        String[] myNameArray = new String[]{
            "Mr. Samete",
            "Ms. Torbura",
            "Mr. Perem",
            "Mr. Rothaw",
            "Miss. Endemos",
            "Mr. Chomoshon",
            "Mrs. Aldir",};
        double[] stipends = new double[]{
            500,
            200,
            300,
            1000,
            250,
            125,
            600,
            338
        };
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        double tally = 0;

        StringBuilder sb = new StringBuilder(128);
        sb.append("<html><table border='0'>");
        for (int index = 0; index < myNameArray.length; index++) {

            String name = myNameArray[index];
            String stipend = nf.format(stipends[index]);

            sb.append("<tr><td align='left'>");
            sb.append(name);
            sb.append("</td><td align='right'>");
            sb.append(stipend);
            sb.append("</td></tr>");

            tally += stipends[index];

        }
        sb.append("<tr><td align='center'>");
        sb.append("</td><td align='right'>");
        sb.append(nf.format(tally));
        sb.append("</td></tr>");

        JOptionPane.showMessageDialog(null, sb.toString());

    }
}

Upvotes: 1

Amarnath
Amarnath

Reputation: 8855

You can append the given input to a String and then pass this to the JOptionPane as input. After getting names from the input just use a String and append all of the names to it for the display.

Example Image

  Arrays.sort(myNameArray);

  String nameString = new String();
  for(int i = 0; i < myNameArray.length; i++) {
      nameString = "\n" + nameString + myNameArray[i] + "\n";
  }

  JOptionPane.showMessageDialog(null,"The Peer Tutors Names are :" + nameString);

Similarly you can do the same approach for other inputs also.

Upvotes: 0

Patashu
Patashu

Reputation: 21773

Solution 1) Build a string from each of the lines. You can add two strings together by simply concatenating them with +, and to put them on separate lines concatenate them with a System.lineSeparator() in between which is a special string that will be whatever the newline ASCII is on your system. (see http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29 )

Solution 2) Add all the lines you want to be in the final string into an ArrayList<String>, then construct the output string by joining your list on System.lineSeparator() concatenation. Similar idea except the lines are logically separate until the very end.

If you need a specific width, I suggest you follow solution 2), except instead of making an ArrayList of the final result you want to print out, make ArrayLists of the components of each column, and note the largest entry in each column. Then, you can add spaces to all the other entries to make them just as large (for example, using a string formatter, the %s token and dynamically adding the width you need, on each entry: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html ). Then you can finally concatenate everything together and spit it out.

Upvotes: 0

Related Questions