I'm doing a method that generates the format for the toString, in matrices, the problem that arises is that it sends me the error:
MissingFormatArgumentException
this is the code I have:
public static void main(String[] args) throws Exception {
int[][] matrixString ={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrixString1 ={{3, 1, 2}, {6, 4, 1}, {2, 1, 1}};
for (int i = 0; i < matrixString.length; i++) {
for (int j = 0; j < matrixString[i].length; j++) {
System.out.print("[" + print(matrixString) + "]");
}
System.out.println();
}
}
public static String[][] print(int[][] matrix){
String[][] formatString;
formatString = new String [matrix.length][matrix[0].length];
String formatLine = toString(matrix);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
formatString[i][j] = String.format(formatLine, matrix[i][j]);
}
}
return formatString;
}
public static String toString(int[][] matrix){
String formatLine = "";
int number = 0;
int cant = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
cant++;
number = matrix[i][j];
String number1 = String.valueOf(number);
System.out.println(number1);
formatLine += ("%" + cant + "$-" + (number1.length() + 1) + "s ");
System.out.println(formatLine);
}
cant = 0;
formatLine += "\n";
}
return formatLine;
}
the error, send it in this line:
formatLine + = ("%" + cant + "$ -" + (number1.length () + 1) + "s");
and at the exit sends me this error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '% -2 $ 2s' at java.util.Formatter.format (Unknown Source) at java.util.Formatter.format (Unknown Source) at java.lang.String.format (Unknown Source) at tests.test.toString1 (test.java.20) at tests.max.test (test.java:9)
I want the format of each line in the matrix to come out like this:
% 1 $ -2s% 2 $ -2s% 3 $ -2s % 1 $ -2s% 2 $ -2s% 3 $ -2s % 1 $ -2s% 2 $ -2s% 3 $ -2s
and depending on the length of the number change