【问题标题】:How to write in between characters in console using Scanner如何使用扫描仪在控制台中的字符之间写入
【发布时间】:2022-01-20 16:42:37
【问题描述】:

我希望能够使用扫描仪在控制台中的字符之间写入。我使用的代码:

    Scanner sc = new Scanner(System.in);
    System.out.print("[customer ID: \t]");
    int id = sc.nextInt();

当前的输出是:

[customer ID:   ]

如果我尝试在括号之间输入,会发生这种情况:

[customer ID:   ]123

有什么方法可以让文本出现在括号之间? 预期输出:

[customer ID: 123]

【问题讨论】:

  • 没有。一旦字符串被发送到控制台(或其他一些输出设备),它就完成了。您无法追溯修改已使用的输出并对其进行修改。您必须创建一个新字符串并将其输出到输出设备。就像打印一张纸,打印出来后直接对纸进行修正。

标签: java input console java.util.scanner


【解决方案1】:

答案是否定的。您需要按回车键 sc.nextInt() 才能读取输入。任何输出都将在下一行,而不是在您输入输入的那一行。

System.out.print("[Customer ID: " + sc.nextInt() + "]";
24
[Customer ID: 524]

我能想到的最接近的是这样的:

System.out.print("Customer ID: ");
int id = sc.nextInt();

产生以下输出:

Customer ID: 1234

【讨论】:

    【解决方案2】:

    这个问题的答案是否定的。一旦输出被发送到控制台(或其他输出设备),它就完成了。您无法追溯修改已使用的输出并对其进行修改。您必须创建一个新输出并将其发送到输出设备。就像打印一张纸,打印出来后直接从程序中对纸进行更正。

    或者,你可以做这样的事情

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your customer ID: ")
    int id = sc.nextInt();
    System.out.print("[customer ID: " + id + "]");
    

    很遗憾,按照您的要求做是不可能的。

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 2017-07-12
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多