我想用 Java 模拟一个模拟 SQL shell。我们的想法是,我们输入一行文本并用 ;
终止它,然后按 Enter 键,该行将打印回控制台。
这应该能够获取多行文本,一旦有 ;
和回车符,它应该打印出文本。
这是我的代码:
while(true){
Scanner scanner = new Scanner(System.in).useDelimiter(";");
StringBuilder builder = new StringBuilder();
while(scanner.hasNextLine()){
if(scanner.nextLine().endsWith(";")){
builder.append(scanner.nextLine());
break;
}else{
builder.append(scanner.nextLine());
}
}
System.out.println(builder.toString());
}
这不起作用,因为它永远不会退出内部 while 循环。
最佳答案
仅供引用: nextLine()
读取行,而不是标记,因此未使用分隔符通过您的代码。
您需要使用 next()
来读取 token ,并且您现在已经意识到,您需要一些条件来结束循环。
结束 shell 的常见方法是使用 exit
命令。
由于您希望语句以 ;
和回车符结尾,因此您需要为此调整分隔符。为了更宽松,在 ;
之后允许空格(正则表达式:\h
水平空白字符),并匹配换行符,而不仅仅是回车符(正则表达式:\R
任何 Unicode 换行序列)。
此外,您需要在任何循环外部创建扫描仪
。
Scanner scanner = new Scanner(System.in).useDelimiter(";\\h*\\R");
for (;;) {
System.out.print(">");
if (! scanner.hasNext())
break;
String stmt = scanner.next();
stmt = stmt.replaceAll("(?mU:^\\s+\\R)|(?U:\\s+$)", ""); // remove blank lines and trailing spaces
if (stmt.equals("exit"))
break;
System.out.println("Received command: " + stmt);
}
System.out.println("Done!");
示例输出
>test;
Received command: test
> This is a
multi-line test
with blank lines
;
Received command: This is a
multi-line test
with blank lines
>
;
Received command:
>exit;
Done!
关于java - Java 中的 Mock SQL shell 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57562323/