【问题标题】:How to make words appear in a list on the terminal?如何让单词出现在终端的列表中?
【发布时间】:2017-11-22 02:42:23
【问题描述】:

假设我这里有这行代码

System.out.println("What is your favorite color 1=blue,2=green,3=yellow,4=orange,5=red,6=purple");

它会在终端上打印出来

你最喜欢什么颜色 1=蓝色 2=绿色 3=黄色 4=橙色 5=红色 6=紫色

一个人怎么会到它像这样弹出它的地方?

你最喜欢什么颜色?

1 = 蓝色

2 = 绿色

3 = 黄色

等等……

有点像终端中的列表,但全部来自一行代码,我发誓我以前知道怎么做,但我不记得了,也找不到任何地方。

【问题讨论】:

  • 使用换行符,\n,即"Line1\nLine2\nLine3"
  • 或者多次调用System.out.println()。
  • 像这样What is your favorite color?\n1 = blue\n2 = green\n3 = yellow?

标签: java


【解决方案1】:

对于 Unix 系统,换行就足够了。

System.out.println("This is the first line\nThis is the second line");

但是,如果我的记忆对我最好的话,我相信在 Windows 上您将需要换行符和回车符?

System.out.println("This is the first line\r\nThis is the second line");

另一种解决方案,如果您总是希望在问题中指定的逗号后打印一个新行。您可以用新行替换逗号。我通常不会推荐此解决方案,但在这种情况下它会起作用。

例如,

String colours = "1=blue,2=green,3=yellow";
colours = colours.replaceAll(",", "\n"); // Or \r\n
System.out.println(colours );

【讨论】:

    【解决方案2】:
    @Test
    public void testInput() throws NumberFormatException, IOException {
    
        final List<String> options = Arrays.asList("blue", "green", "yellow", "orange", "red", "purple");
    
        final StringBuilder sb = new StringBuilder("What is your favorite color\n");
        IntStream.range(0, options.size()).forEach(i -> sb.append(i).append("=").append(options.get(i)).append("\n"));
    
        System.out.println(sb.toString());
    
        final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        final int value = Integer.parseInt(in.readLine());
        if (value >= 0 && value < options.size()) {
            System.out.println("You choose " + options.get(value) + " (" + value + ")");
        } else {
            System.err.println("Invalid input (" + value + ")");
        }
    }
    

    作为一个更扩展的答案并使用看起来很酷的流 - 但一个简单的 for 循环也可以;-)

    【讨论】:

    • 谢谢,这就是我现在编写代码的方式,但我正在尝试尽可能简化这一点,因为我的朋友就像刚开始在 Java 上学一样,但我想通了
    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2020-07-19
    • 2010-12-14
    • 2013-10-18
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多