2015-12-16 8 views
2

出于某种原因,我的循环只在我的for循环的第一次迭代后输出“\ t”。 这里是我的循环代码:什么导致我的循环只在第一次迭代中忽略这个“ t”?

input = -1; 
private String[] types = {"none", "vanilla", "hazelnut", "peppermint", "mocha", "caramel"}; 
while ((input < 0) || (input > (types.length - 1))){ //gets user's latte flavor input 
     System.out.println("Enter the number corresponding to the latte type you would like:"); 
     for (int i = 0; i < types.length; i++){ 
      if (i <= (types.length - 2)){ //prints two options per line 
       System.out.println(i + ": " + types[i] + "\t" + (i + 1) + ": " + types[i + 1]); 
      } 
      else if (i == (types.length - 1)){ 
       System.out.println(i + ": " + types[i]); 
      } 
      else{ //does nothing on odd indices 
      } 
      i++; 
     } 
     input = keyboard.nextInt(); 
    } 

此输出以下:

Enter the number corresponding to the latte type you would like: 
0: none  1: vanilla 
2: hazelnut  3: peppermint 
4: mocha  5: caramel 

我们可以看到,“1:香草”不以同样的方式在其他行的间隔。我对我的茶类代码,然而,正常工作:

input = -1; 
private String[] types = {"white", "green", "oolong", "black", "pu-erh", "camomille"}; 
while ((input < 0) || (input > (types.length - 1))){ //gets user's tea flavor input 
     System.out.println("Enter the number corresponding to the tea type you would like:"); 
     for (int i = 0; i < types.length; i++){ 
      if (i <= (types.length - 2)){ //prints two options per line 
       System.out.println(i + ": " + types[i] + "\t" + (i + 1) + ": " + types[i + 1]); 
      } 
      else if (i == (types.length - 1)){ 
       System.out.println(i + ": " + types[i]); 
      } 
      else{ //does nothing on odd indices 
      } 
      i++; 
     } 
     input = keyboard.nextInt(); 
    } 

而这种输出以下:

Enter the number corresponding to the tea type you would like: 
0: white 1: green 
2: oolong 3: black 
4: pu-erh 5: camomille 

是什么原因导致我的拿铁循环(我的咖啡循环也受到这个间距问题)来输出不同比我的茶圈?感谢您帮助我理解这种行为!

+0

我已经为你的问题提出了一个'printf()'解决方案...这可能是最简单的方法来处理你的问题 – ParkerHalo

回答

3

由于还没有,我会提供一个解决方案,使用printf。你可以只用一个格式(如System.out.printf()格式化字符串):

System.out.printf("%d: %-12s%d:%-12s\n", i, types[i], i+1, types[i+1]); 
  • %d允许你输入一个整数类型。
  • %-12s允许你输入一个字符串(最小长度是12左对齐)......这将取代你的标签!
+0

谢谢,这工作。我总是忘记java移植在我最喜欢的打印功能! – shtuken

5

那么TAB实际上就在那里。请注意,0: none比您发布的其他示例短一个字符。所以你选择了一个更早的制表位。

+0

你可能会建议一种治疗方法,可能是'String.format()','Formatter'或'PrintStream.printf()' –

+0

感谢您的解释。我想知道为什么看起来这个标签不是简单地缩进一定的空间。 – shtuken

1

none与其他人相比是个小字。为了解决这个问题,可以在types数组中填充空格的单词,使其具有相同的长度。

1

选项卡很棘手,因为它们受线位置和选项卡宽度的影响。

更好地使用空格填充。使用Apache Commons方便的方法:

StringUtils.rightPad(types[i], COLUMN_WIDTH) 

(根据您的最长调整文本COLUMN_WIDTH

-1

这是因为你的数组的第一个字符串的长度引起的。试试用“nonee”而不是“none”来查看。

如果你想正确地做,你应该使用某种填充。

0

以下是格式

System.out.println(i + ": " + String.format("%-5s\t", types[i]) + (i + 1) + ": " + types[i + 1]); 

这将解决这个问题的修复程序。

+0

这解决了我在本地测试时遇到的问题。为什么有一个downvote? – Thanga

-1

该选项卡如上所述存在。至于为什么事情不一致。你可以参考这link

相关问题