Java错误 - 未知格式转换异常

时间:2014-06-15 19:50:41

标签: java formatting printf

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-'

    at java.util.Formatter.checkText(Formatter.java:2579)
    at java.util.Formatter.parse(Formatter.java:2565)
    at java.util.Formatter.format(Formatter.java:2501)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at IntGrid.printGrid(IntGrid.java:28)
    at IntGrid.main(IntGrid.java:20)

所以这就是我得到的错误。我猜它与printf行的格式有关,但我不确定如何修复它。试图打印一个整数并在它之后有一些空格来使总宽度为5个字符。

我的代码:

import java.util.*;

public class IntGrid {
public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    System.out.println("Please enter a number of rows:");
    int rows = reader.nextInt();
    System.out.println("Please enter a number of columns:");
    int columns = reader.nextInt();

    printGrid(rows, columns);

}

public static void printGrid(int rows, int columns) {
    int start = 1;
    for (int i = 1; i <= rows; i ++) {
        for (int j = 1; j <= columns; j = j + rows) {
            System.out.printf("%-5.d", j);
        }
        System.out.println();
    }
}
}

任何提示?

1 个答案:

答案 0 :(得分:0)

你可能想要这个:

System.out.printf("%-5d", j);

因为.(小数点)用于浮点数/双打。