2017-10-05 44 views
-3

如何使用'System.out.printf'来使我的代码看起来需要。 我想我的计算看起来像这样:如何使用'System.out.printf'格式化我的输出?

this is how I want my code to look alike.
不喜欢这样的:

I dont want it to look like this

现在,如果声明,但我不得不用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(""); 

} 

}

+3

你尝试过这么远吗? – Mureinik

+1

查看https://docs.oracle.com/javase/tutorial/java/data/characters.html可能会有帮助。 – Austin

+0

这很有用:https://www.cs.colostate.edu/~cs160/.Spring16/resources/Java_printf_method_quick_reference.pdf – tommyO

回答

-1

您还可以使用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); 
} 

OUTPUT:

3 6 9 12 15 
    18 21 24 27 30 
+0

该解决方案非常糟糕。只需使用printf格式。 – DwB

+0

@DwB解决方案只有1行。其余的是打印一个示例输出,所以OP知道它是如何工作的。 – user3437460

+0

@Stefan基本上,我的答案与String.format(“%1 $ 4s”,i)“一样简单,其中'i'就是你的价值。 – user3437460

0

重用你的一些变种名称

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