系统输出中的Java选项卡

时间:2016-09-16 10:47:12

标签: java

我必须创建一个应用程序,我将打印学生的结果。在作业中,我们必须使用\t,以便将所有内容排成一行。

   for(int i = 0; i< 7; i++) {
         System.out.println("Vak/Project :" + naamVak[i] + "\t\tCijfer: " +
      inputCijfer[i] + "\tBehaalde studiepunten: " + studiepuntenVAK[i]);
   }

它会打印项目名称(名为naamVak的数组),结果(inputCijfer)以及每个项目获得的点数(studiepuntenVak)。

当我将结果打印到控制台时,它显示如下:

Vak/Project :Fasten Your Seatbelts      Cijfer: 1.0 Behaalde studiepunten: 0
Vak/Project :Programming        Cijfer: 2.0 Behaalde studiepunten: 0
Vak/Project :Databases      Cijfer: 3.0 Behaalde studiepunten: 0
Vak/Project :Personal Skills        Cijfer: 4.0 Behaalde studiepunten: 0
Vak/Project :Project Skills     Cijfer: 5.0 Behaalde studiepunten: 0
Vak/Project :Infrastructure     Cijfer: 6.0 Behaalde studiepunten: 3
Vak/Project :Network Engineering 1      Cijfer: 7.0 Behaalde studiepunten: 3

如何将输出创建为正确的行?

3 个答案:

答案 0 :(得分:1)

您可以使用String.format方法(使用类似printf的语法),并为width提供值。语法在这里:https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax,你可以使用like:

System.out.println(String.format("%20s %20s %20s", naamVak[i], inputCijfer[i], studiepuntenVAK[i]));

这假设每列的最大输入宽度为20个字符

答案 1 :(得分:0)

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

您可以使用String.format方法

String s1 = String.format("test right alignment:  %13s   %50s  ",'test a short string', 'test a very very very long string' );
String s2 = String.format("test left  aligmnent:  %-13s   %-50s  ",'test a short string', 'test a very very very long string'  );

System.out.println(s1);
System.out.println(s2);

答案 2 :(得分:0)

System.out.println(String.format("%20s %20s %20s %20s %20s", "Vak/Project: ", naamVak[i], "Cijfer: ", inputCijfer[i], "Behaalde studiepunten: ", studiepuntenVAK[i]));

仍然为用户提供了一个奇怪的视图。这是控制台中的输出:

   Vak/Project:  Fasten Your Seatbelts             Cijfer:                   8.6 Behaalde studiepunten: 
   Vak/Project:           Programming             Cijfer:                   7.5 Behaalde studiepunten: 
   Vak/Project:             Databases             Cijfer:                   2.1 Behaalde studiepunten: 
   Vak/Project:       Personal Skills             Cijfer:                   2.3 Behaalde studiepunten: 
   Vak/Project:        Project Skills             Cijfer:                   2.4 Behaalde studiepunten: 
   Vak/Project:        Infrastructure             Cijfer:                   2.5 Behaalde studiepunten: 
   Vak/Project:  Network Engineering 1             Cijfer:                   2.6 Behaalde studiepunten: