首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是什么导致我的循环只在第一次迭代中忽略这个"\t“呢?

是什么导致我的循环只在第一次迭代中忽略这个"\t“呢?
EN

Stack Overflow用户
提问于 2015-12-16 08:48:36
回答 7查看 134关注 0票数 2

出于某种原因,我的循环只在For -循环的第一次迭代之后输出“t”。下面是我的循环代码:

代码语言:javascript
复制
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();
    }

这将产生以下结果:

代码语言:javascript
复制
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“的行距与其他行不同。但是,我的茶类代码工作正常:

代码语言:javascript
复制
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();
    }

这将产生以下结果:

代码语言:javascript
复制
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循环也遭受这个间隔问题)输出与我的茶循环不同?谢谢你帮助我理解这种行为!

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2015-12-16 09:31:53

由于目前还没有,所以我将使用printf提供解决方案。您只需使用格式化程序(如System.out.printf()来格式化字符串):

代码语言:javascript
复制
System.out.printf("%d: %-12s%d:%-12s\n", i, types[i], i+1, types[i+1]);
  • %d允许您输入整数类型。
  • %-12s允许您输入字符串(最小长度为12左对齐).这取代了你的标签!
票数 3
EN

Stack Overflow用户

发布于 2015-12-16 08:51:18

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

票数 5
EN

Stack Overflow用户

发布于 2015-12-16 08:54:45

与其他单词相比,none是一个很小的单词。为了解决这个问题,您可以将单词放在types数组的末尾加上空格,使其具有相同的长度。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34307453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档