【发布时间】: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