【问题标题】:How do I put characters in front of userInput on a console? [duplicate]如何在控制台上的 userInput 前面放置字符? [复制]
【发布时间】:2021-08-14 04:45:33
【问题描述】:

我正在codiva.io.. 上制作控制台游戏,我想在用户输入的文本前放置一些字符。基本上,我想知道如何强制用户在按下回车键之前输入一些字符。

示例代码:

import java.util.Scanner;
class test {
  public static void main(String[] args) {
    System.out.println("        | Welcome to the [...] Game!\n");
       Scanner useri = new Scanner(System.in);
       String userin = useri.nextLine();
        if (userin.equals("devcom")){
          System.out.println("\nCommands| Communication with developer channel [ACTIVATED]\n");
         Scanner useris = new Scanner(System.in);
          String userins = useris.nextLine();                                          
         if (userins.matches("^~sg\\h+(\\S+(?:\\h+\\S+)*)$")){
           System.out.println("\n>>>>>>>>|");
           System.out.println("Commands| Test command successful. Communication to developer channel [DEACTIVATED]");
           System.out.println(">>>>>>>>|\n");
         }
       } 
  }
}

输出:

对于正常的控制台输出,我使用:

"        | "

对于我使用的命令:

">>>>>>>>| "
"Commands| "
">>>>>>>>| "

我的问题是,如何输入正常的控制台输出:

"        | "

在用户输入的文字之前?

例如;在上面写着“devcom”的地方,我输入了 devcom,(在照片 1 中),我想让它说:

"        | devcom"

即使用户只键入“devcom”部分。

【问题讨论】:

  • println 在打印后添加换行符。 System.out.print(" | ");(随后是 useris.next(); 调用)将满足您的需求。
  • @BeUndead 我不太确定我是否理解你的回答。你能详细说明一下吗?
  • Here's an example。不幸的是,上面的“输出”选项卡没有将标准输入复制到它……但它可以在普通控制台中使用。
  • 在你使用nextLine();之前,你可以使用System.out.print(" | ");,将它预先输入到控制台,然后在检查输入时你需要包含它if (userin.equals(" | devcom")){...
  • @BeUndead 它有效! “尝试”和“最终”有什么作用?

标签: java console command java.util.scanner user-input


【解决方案1】:

为了达到你想要的结果,你必须把:

System.out.print("        | ");

行前:

String userins = useris.nextLine(); 

这样,在控制台可以检查下一行之前,您在 userInput 之前打印了您想要的文本。因此在 userInput 之前输入文本。

【讨论】:

  • 有人投了反对票,因为我给出了正确的答案......为什么......
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
相关资源
最近更新 更多