[英]break program when user enters specific string into input
I want to make it so that the user inputs some string, and the program takes console input until user types "/done".. so here's how it would work:我想让用户输入一些字符串,程序接受控制台输入,直到用户输入“/done”..所以它是如何工作的:
print to user: enter your string打印给用户:输入您的字符串
user enters: hello eclipse.用户输入:你好日食。
hi test blah blah嗨测试等等等等
bla 456 testmore /done bla 456 testmore /done
As soon as user enters /done within any string of any size, the program breaks.只要用户在任何大小的任何字符串中输入 /done,程序就会中断。 The program would NOT end if you hit "enter" key.
如果您按“回车”键,程序将不会结束。 It would only end if you type in /done.. How I setup my program so far:
它只会在您输入 /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"));
I tried putting under while loop there something like below but I don't think I am doing it right.我尝试在 while 循环下放置如下所示的内容,但我认为我做得不对。
while (!input.equals("/done"));
if input.equals("/done");
break;
}
I understand that with a do-while loop, it continues as long as boolean in while is false.我知道使用 do-while 循环,只要 while 中的布尔值是假的,它就会继续。 So for my program, program takes inputs until user types in /done so boolean is false until string /done in inputted.
所以对于我的程序,程序接受输入直到用户输入 /done 所以布尔值是假的,直到输入字符串 /done 。 Then according to the logic above, the program breaks as soon as input equals "/done"
然后根据上面的逻辑,一旦输入等于“/完成”,程序就会中断
Any ideas on what I'm doing wrong?关于我做错了什么的任何想法?
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;
}
}
I think this will work fine我认为这会正常工作
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.