[英]break program when user enters specific string into input
我想讓用戶輸入一些字符串,程序接受控制台輸入,直到用戶輸入“/done”..所以它是如何工作的:
打印給用戶:輸入您的字符串
用戶輸入:你好日食。
嗨測試等等等等
bla 456 testmore /done
只要用戶在任何大小的任何字符串中輸入 /done,程序就會中斷。 如果您按“回車”鍵,程序將不會結束。 它只會在您輸入 /done 時結束.. 到目前為止我是如何設置我的程序的:
Scanner 123 = new Scanner(System.in);
string input = "";
System.out.println("Enter your string: ");
do {
input = 123.nextLine();
System.out.print("Rest of program here..");
}
while (!input.equals("/done"));
我嘗試在 while 循環下放置如下所示的內容,但我認為我做得不對。
while (!input.equals("/done"));
if input.equals("/done");
break;
}
我知道使用 do-while 循環,只要 while 中的布爾值是假的,它就會繼續。 所以對於我的程序,程序接受輸入直到用戶輸入 /done 所以布爾值是假的,直到輸入字符串 /done 。 然后根據上面的邏輯,一旦輸入等於“/完成”,程序就會中斷
關於我做錯了什么的任何想法?
Scanner s=new Scanner(System.in);
String input = "";
String[] parts;
System.out.println("Enter your string: ");
while (true){
input=s.nextLine();
if (input.contains("/done")){
parts=input.split("/done");
//Use parts[0] to do any processing you want with the part of the string entered before /done in that line
break;
}
}
我認為這會正常工作
Scanner scanner = new Scanner(System.in);
String input = "";
System.out.println("Enter your string: ");
do {
input = scanner.nextLine();
} while (!input.contains("/done"));
System.out.print("Rest of program here..");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.