出于某种原因,我的循环只在For -循环的第一次迭代之后输出“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: vanilla“的行距与其他行不同。但是,我的茶类代码工作正常:
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是什么原因导致我的拉丁循环(我的Espresso循环也遭受这个间隔问题)输出与我的茶循环不同?谢谢你帮助我理解这种行为!
发布于 2015-12-16 09:31:53
由于目前还没有,所以我将使用printf提供解决方案。您只需使用格式化程序(如System.out.printf()来格式化字符串):
System.out.printf("%d: %-12s%d:%-12s\n", i, types[i], i+1, types[i+1]);%d允许您输入整数类型。%-12s允许您输入字符串(最小长度为12左对齐).这取代了你的标签!发布于 2015-12-16 08:51:18
TAB实际上就在那里。请注意,0: none比您发布的其他示例短一个字符。所以你选择一个较早的制表符。
发布于 2015-12-16 08:54:45
与其他单词相比,none是一个很小的单词。为了解决这个问题,您可以将单词放在types数组的末尾加上空格,使其具有相同的长度。
https://stackoverflow.com/questions/34307453
复制相似问题