Ok what I have currently is the blelow code in a for loop and this works fine it just doesn't format the text.

outString = outString + "  " + i + "         " + numArray[i] + "\n";

I am trying to format the text of i to right justify 6 spaces and numArray 16. i is an int and numArray is a double.

my attempst at this are...

outString = String.format(outString,%6d,%16f,i,numArray[i],"\n")

and

outString = outString+String.format(%6d,%16f,i,numArray[i])+"\n";

Any help or direction would be greatly appreciated.

First of all the format String must not change. It is the one the determines how the output will be formatted:

outString = String.format(outString,%6d,%16f,i,numArray[i],"\n")
 
//or

outString = outString+String.format(%6d,%16f,i,numArray[i])+"\n";

After the first loop you change the outString so the rest of the results will be all over the place.
You need to store the result into another String:

String formatStr = "....";

// from the API:
String result = String.format(formatStr, [B][U]arguments[/U][/B]);

The format String would be like a way of saying how the arguments will be printed. String formatStr = "I: %6d, Value: %16d"; The %6d, %16d will be replaced by the arguments of the String.format method: String result = String.format(formatStr,[B][U]i,numArray[i][/U][/B]); You don't need the "\n". If you want a new line just use System.out.println.

Edited 7 Years Ago by javaAddict: n/a

I think I see what you are saying. I am getting the same rsults as before though.

@Override
    public String toString() {
        String formatStr = "%6d %16.2f";
        String outString = "";
        for (int i = 0; i < number.length; i++) {
            String result = String.format(formatStr, i, number[i]);
            outString = outString + result + "\n";
        }
        return outString;
    }
}

I know I still need to change "\n" but is this or is this not what you meant javaaddict?


The format String would be like a way of saying how the arguments will be printed. String formatStr = "I: %6[B]d[/B], Value: %16[B]d[/B]"; The %6d, %16d will be replaced by the arguments of the
....

Is the number[] an array of ints or an array of floats ?
And it would be helpful if you posted the errors that you are getting.

Your code works for me only if the array is an array of floats. I believe that the API has a list that says when to use what ("%f or %d")

It is an array of doubles and I am not getting any errors, it works just fine in all the ways I have posted. It just isn't formatting properly.
This is how it is currently outputting

1      0.00
  2      0.00
  3      0.00
  4      0.00
  5      0.00
  6      0.00
  7      0.00
  8      0.00
  9      0.00
  10      0.00
  11      0.00

this is how I want it to output

1      0.00
 2      0.00
 3      0.00
 4      0.00
 5      0.00
 6      0.00
 7      0.00
 8      0.00
 9      0.00
10      0.00
11      0.00

ignore the black numbers to the left of the red numbers

It is an array of doubles and I am not getting any errors, it works just fine in all the ways I have posted. It just isn't formatting properly.
This is how it is currently outputting

1      0.00
  2      0.00
  3      0.00
  4      0.00
  5      0.00
  6      0.00
  7      0.00
  8      0.00
  9      0.00
  10      0.00
  11      0.00

this is how I want it to output

1      0.00
 2      0.00
 3      0.00
 4      0.00
 5      0.00
 6      0.00
 7      0.00
 8      0.00
 9      0.00
10      0.00
11      0.00

ignore the black numbers to the left of the red numbers

Well I believe that it's time to show your code. And probably the error is that your array is empty, you didn't put any values in it. And if you did at some point in your program, then you are not passing the array that has values in it.

Sorry for replying so late. The holiday has been extremely busy. So here is the code. The elements of the array are entered as the program runs. When I put all zeros that is just the default before entering any into the array.

package lab10;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.String;
import java.io.PrintStream;

public class ExceptHandleAryDouble extends JFrame {
    // Member variables

    private JLabel prompt1, prompt2, prompt3;   // Prompts for user input
    private JTextField input1, input2, input3;  // Mechanisms to get user input
    private JButton button1;
    private final int MIN_INDEX = 0;
    private final int MAX_INDEX = 11;
    private final int MAX_ITEMS = 12;  // Max number of elements in the array
    private MyNumberArrayD numArray = new MyNumberArrayD(MAX_ITEMS);
    private JTextArea TDisplay;        // Output display area
    private int TDisplayWidth = 30;    // Width of the JTextArea
    private int TDisplayHeight = 25;   // Height of the JTextArea

    // The main method required for an application program
    public static void main(String[] args) {
        JFrame frame = new ExceptHandleAryDouble(); // Construct the window
        frame.setSize(new Dimension(550, 500));  // Set its size
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);   // Make the window visible
    }

    // Constructor
    public ExceptHandleAryDouble() {
        super("Exception Handling original Lab");
        setLayout(new BorderLayout());

        JPanel pan = new JPanel(new GridLayout(3, 2));
        add(pan, BorderLayout.NORTH);
        EtchedBorder eBorder = new EtchedBorder();

        prompt1 = new JLabel("Enter index number (0-" + (MAX_ITEMS - 1) + "), hit Enter key:", JLabel.RIGHT);
        prompt1.setBorder(eBorder);
        pan.add(prompt1);  // put prompt on panel
        input1 = new JTextField(4);
        pan.add(input1);  // put input JTextField on panel

        prompt2 = new JLabel("Enter decimal number to insert, hit Enter key:", JLabel.RIGHT);
        prompt2.setBorder(eBorder);
        pan.add(prompt2);  // put prompt on panel
        input2 = new JTextField(15);
        pan.add(input2);  // put input JTextField on panel

        prompt3 = new JLabel("Sum and Average of entered numbers:", JLabel.RIGHT);
        prompt3.setBorder(eBorder);
        pan.add(prompt3);  // put prompt on panel

        button1 = new JButton("Compute");
        pan.add(button1);  // put button on panel

        // Create and display a text area for presenting results
        TDisplay = new JTextArea(createListStr(),
                TDisplayHeight, TDisplayWidth);
        TDisplay.setLineWrap(true);
        TDisplay.setWrapStyleWord(true);
        add(TDisplay, BorderLayout.CENTER);

        // Add handlers to respond to user GUI manipulation
        input1.addActionListener(new ActListener1());
        input2.addActionListener(new ActListener2());
        button1.addActionListener(new ButtonListener());
    }

    public String createListStr() {
        String format = "%6s %16s";
        String value = "Value";
        String index = "Index";
        String formatStr = String.format(format, index, value);
        String outString = "";
        outString = "\nTHE NUMBER LIST:\n\n" + formatStr + "\n" + numArray.toString();
        return outString;
    }
// Class to handle user action on first JTextField
// Class to handle user action on first JTextField

    class ActListener1 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            int pos = 0;
            String strPos = input1.getText();
            String strValue = input2.getText();
            try {
                pos = Integer.parseInt(strPos);
                try {
                    if (pos < MIN_INDEX || pos > MAX_INDEX) {
                        throw new Exception("Index out of bounds");
                    }
                } catch (Exception ob) {
                    String output2 = "Index is out of bounds\n" +
                            "Exception occured after pressing enter in the first textfield\n" +
                            "Re-enter a selection in the range of " + MIN_INDEX + " - " + MAX_INDEX;
                    ob.toString();
                    JOptionPane.showMessageDialog(null, output2);
                    return;
                }
            } catch (Exception ex1) {
                String output1 = "Incorrect datatype entered for textfield 1\n" +
                        "Occured after pressing enter in the 1st textfield\n" +
                        "Enter appropriate datatype\n" + ex1.toString();
                JOptionPane.showMessageDialog(null, output1);
                return;
            }
            try {
                double value = Double.parseDouble(strValue);
                numArray.insertNumberAtPos(value, pos);
            } catch (Exception ex2) {
                String output2 = "Incorrect datatype entered for textfield 2\n" +
                        "Occured after pressing enter in the 1st textfield\n" +
                        "Enter appropriate datatype\n" + ex2.toString();
                JOptionPane.showMessageDialog(null, output2);
                return;
            }
            // Display list and results
            TDisplay.setText(createListStr());
        }
    }

    // Class to handle user action on second JTextField
    class ActListener2 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            int pos = 0;
            String strPos = input1.getText();
            String strValue = input2.getText();
            try {
                pos = Integer.parseInt(strPos);
                try {
                    if (pos < MIN_INDEX || pos > MAX_INDEX) {
                        throw new Exception("Index out of bounds");
                    }
                } catch (Exception ob) {
                    String output2 = "Index is out of bounds\n" +
                            "Exception occured after pressing enter in the second textfield\n" +
                            "Re-enter a selection in the range of " + MIN_INDEX + " - " + MAX_INDEX;
                    ob.toString();
                    JOptionPane.showMessageDialog(null, output2);
                    return;
                }
            } catch (Exception ex1) {
                String output1 = "Incorrect datatype entered for textfield 1\n" +
                        "Occured after pressing enter in the 2nd textfield\n" +
                        "Enter appropriate datatype\n" + ex1.toString();
                JOptionPane.showMessageDialog(null, output1);
                return;
            }
            try {

                double value = Double.parseDouble(strValue);
                numArray.insertNumberAtPos(value, pos);
            } catch (Exception ex2) {
                String output2 = "Incorrect datatype entered for textfield 2\n" +
                        "Occured after pressing enter in the 2nd textfield\n" +
                        "Enter appropriate datatype\n" + ex2.toString();
                JOptionPane.showMessageDialog(null, output2);
                return;
            }
            // Display list and results
            TDisplay.setText(createListStr());
        }
    }

    // Class to handle user action on button
    class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            input1.setText("");
            input2.setText("0.0");
            String displayStr = createListStr();
            try {
                if (numArray.getCountOfEnteredNumbers() == 0) {
                    throw new ArithmeticException("Divisor can not be zero");
                }
                if (e.getSource() == button1) {
                    displayStr += "\nNumber of entered decimal numbers is: " + numArray.getCountOfEnteredNumbers();
                    displayStr += "\nSum of the entered numbers is: " + numArray.computeSumOfNumbers();
                    displayStr += "\nAverage of the entered numbers is: " + numArray.computeAveOfEnteredNumbers();
                }
            } catch (ArithmeticException ex) {
                String output1 = "Array is empty, Can not divide by zero\n" +
                        "Please complete an entry before pressing compute\n" +
                        ex.toString();
                JOptionPane.showMessageDialog(null, output1);
                return;
            }
            // Display list and results
            TDisplay.setText(displayStr);
        }
    }
}

// A simple array class to use for demonstrating exception handling
class MyNumberArrayD {
    // Instance variables

    private int maxSize;       // Maximum number of elements in the array
    private double number[];   // The array of numbers
    private int countNums = 0;

    // Constructor
    MyNumberArrayD(int mSize) {
        number = new double[mSize];
        maxSize = mSize;
    }

    // Method to return the number of elements that have been entered into the array
    public int getCountOfEnteredNumbers() {
        return countNums;
    }

    // Method to insert number into array at index position j
    public void insertNumberAtPos(double val, int j) {
        number[j] = val;
        countNums++;
    }

    // Method to get the data number at array index position j
    public double getNumberAtPos(int j) {
        return number[j];
    }

    // Method to compute the sum of all the numbers in the array
    public double computeSumOfNumbers() {
        double sum = 0.0;
        for (int i = 0; i < number.length; i++) {
            sum += number[i];
        }
        return sum;
    }

    // Method to compute the average of all the numbers actually inserted into the array
    public double computeAveOfEnteredNumbers() {
        double sum = computeSumOfNumbers();
        double ave = sum / countNums;
        return ave;
    }

    // Method to return the entire array composed as one string, with both index
    // and element value included
    @Override
    public String toString() {
        String formatStr = "%6d %16.2f";
        String outString = "";
        for (int i = 0; i < number.length; i++) {
            String result = String.format(formatStr, i, number[i]);
            outString = outString + result + "\n";
        }
        return outString;
    }
}

I run your code and as you can see it outputs correctly:

public static String toString2(float [] number) {
        String formatStr = ">%6d %16.2f";
        String outString = "";
        for (int i = 0; i < number.length; i++) {
            String result = String.format(formatStr, i, number[i]);
            outString = outString + result + "\n";
        }
        return outString;
    }


    public static void main(String [] args) {
        float [] num = new float[12];
        System.out.println(toString2(num));
    }

The problem might be with the way the TextArea renders the results.
Have you tried displaying only the toString method at the JTextArea? As you can see above, if you run the example, it displays at the console the format that you want

I tried that with no difference. I am wondering if the integers and floats need to be converted back to a string rather than their numerical counterparts. The reason I ask is these format correctly. Which are the headers above both columns.

public String createListStr() {
   String format = "%6s %16s";
   String value = "Value";
   String index = "Index";
   String formatStr = String.format(format, index, value);
   String outString = "";
   outString = "\nTHE NUMBER LIST:\n\n" + formatStr + "\n" + numArray.toString();
   return outString;
}
This article has been dead for over six months. Start a new discussion instead.