2 回答

TA貢獻1845條經(jīng)驗 獲得超8個贊
僅供參考: nextLine()讀取lines,而不是tokens,因此您的代碼未使用定界符。
您需要使用next()來讀取標(biāo)記,正如您現(xiàn)在意識到的那樣,您需要一些條件來結(jié)束循環(huán)。
結(jié)束 shell 的常用方法是exit命令。
;由于您希望語句以回車符結(jié)尾,因此您需要為此調(diào)整分隔符。為了更寬松,在;(正則表達式:\h水平空白字符)之后允許空格,并匹配換行符,而不僅僅是回車符(正則表達式:\R任何 Unicode 換行符序列)。
此外,您需要創(chuàng)建Scanner 外部任何循環(huán)。
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!

TA貢獻1836條經(jīng)驗 獲得超4個贊
為什么不檢查每一行是否包含;?如果是,則附加相關(guān)值并跳出循環(huán)。
while(true){
Scanner scanner = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if (line.contains(";"))
{
String[] parts = line.split(";");
if (parts.length > 0)
{
builder.append(parts[0] + ";");
}
else
{
builder.append(";");
}
break;
}
else
{
builder.append(line);
}
}
System.out.println(builder.toString());
}
添加回答
舉報