如何使用'System.out.printf'使我的代码看起来需要。 我希望我的计算看起来像这样:
不喜欢这样:
现在我使用if语句,但我必须使用printf。
public static void main(String[] args) {
//Maken van een scanner met de naam input
Scanner input = new Scanner(System.in);
System.out.print("Welke tafel wilt u printen? ");
int tafelGetal = input.nextInt();
int nummer = 0;
int maxGetal = 10;
System.out.println("De tafel van " + tafelGetal + ":");
do {
int nummer2;
nummer2 = ++nummer;
nummer = nummer2;
int berekening = tafelGetal * nummer;
if (nummer >= 5) {
System.out.print("\t" + berekening + "\t");
}
if (nummer == 5) {
System.out.println(" ");
}
if (nummer < 5) {
System.out.print("\t" + berekening + "\t");
}
} while (nummer != maxGetal);
System.out.println("");
}
}
答案 0 :(得分:0)
重用一些var名称
int tafelGetal = 3;
int maxGetal = 10;
int numberPerLine = 5;
int columnWidth = 4;
for (int i = 1; i <= maxGetal; i += numberPerLine) { //iterate over output lines
for (int j = 0; j < numberPerLine && i + j <= maxGetal; j++) { //iterate over columns
int berekening = (i + j) * tafelGetal;
System.out.printf("%" + columnWidth + "d", berekening);//format as number with specified width
}
System.out.println();
}
有关可用格式的更多详细信息,请访问: https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html
答案 1 :(得分:-1)
您也可以使用THROW
来实现这一目标:
示例:强>
String.format()
<强>输出:强>
for(int i=3; i<=15; i+=3)
System.out.print( p(i, 4) );
System.out.println();
for(int i=18; i<=30; i+=3)
System.out.print( p(i, 4) );
//for padding the string
public static String p(int val, int spaces) {
return String.format("%1$" + spaces + "s", val);
}