0

First of all, I have this input:

[[0.0, 1.0, 0.6666666666666666, -0.3333333333333333, 0.0, 0.0, 1.3333333333333333], [1.0, 0.0, -0.3333333333333333, 0.6666666666666666, 0.0, 0.0, 3.3333333333333335], [0.0, 0.0, -1.0, 1.0, 1.0, 0.0, 3.0], [0.0, 0.0, -0.6666666666666666, 0.3333333333333333, 0.0, 1.0, 0.6666666666666667], [0.0, 0.0, -0.3333333333333333, -1.3333333333333333, 0.0, 0.0, -12.666666666666666]];

Then I want to output this input formatted. There are some rules:

  • Replace [ for "";
  • Replace ] for "\n";
  • Replace , for ""; // Remove commas between elements
  • Replace "." for ","; // Change dot to comma
  • Truncate at the 2nd decimal place; // 1.33333 -> 1.33

So, here's my code for while:

@Override
public String toString() {
   StringBuilder sb = new StringBuilder("\n");

   sb.append("\n").append(numbersOfExmaple.toString()
           .replaceAll("\\[", "")
           .replaceAll("\\]", "\n")
           .replaceAll(",", "")
           .replaceAll("\\.", ","));
           // String.format isn't working...
    return sb.toString();
}

Actually the output is (note there's a whitespace in the beggining, I want to remove it also):

0,0 1,0 0,6666666666666666 -0,3333333333333333 0,0 0,0 1,3333333333333333
 1,0 0,0 -0,3333333333333333 0,6666666666666666 0,0 0,0 3,3333333333333335
 0,0 0,0 -1,0 1,0 1,0 0,0 3,0
 0,0 0,0 -0,6666666666666666 0,3333333333333333 0,0 1,0 0,6666666666666667
 0,0 0,0 -0,3333333333333333 -1,3333333333333333 0,0 0,0 -12,666666666666666

Expected output:

 0,00   1,00   0,67  -0,33   0,00   0,00   1,33 
 1,00   0,00  -0,33   0,67   0,00   0,00   3,33 
 0,00   0,00  -1,00   1,00   1,00   0,00   3,00 
 0,00   0,00  -0,67   0,33   0,00   1,00   0,67 
 0,00   0,00  -0,33  -1,33   0,00   0,00  -12,67

3 Answers 3

1

Try something like this

private static String matrixString(Double[][] numbersOfExmaple) {
    StringBuilder answ = new StringBuilder();

    for (Double[] arr : numbersOfExmaple) {
        for (Double val : arr) {
            answ.append(String.format("%7.2f", val).replace('.', ','));
        }
        answ.append('\n');
    }

    return answ.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

0

1 You can parse the string to array 2 truncate decimal 3 print your array elements 1 by 1 ,before print replace . By ,

Comments

0

You can use this kind of method

for(ArrayList<Double> tmp:ad){
      for(Double t:tmp)
            System.out.print(String.format("%.2f ",t).replace(".",","));
      System.out.println();
}

Here ad id the arraylist of arraylist add tmp is ArrayList<Double>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.