+ 3

(JAVA) Finding a string inside a string

Hey guys, Having a bit of trouble here. I have been tasked with creating a chatbot and one of the specifications is displaying an error message if the user inputs a exclamation mark at any time. I have tried basic while-do loops etc but have had no luck. Any/all help is appreciated. Thanks.

3rd Apr 2018, 10:13 AM
Jokitsa
Jokitsa - avatar
8 Réponses
+ 5
You could do this: While(!input.contains("!")) Or if it should only display the error when an exclamation point is entered by itself you could do: While(input.equals("!")) Hope this helps!
3rd Apr 2018, 10:21 AM
Justin Hinkle
Justin Hinkle - avatar
+ 14
String input = ... // the user input if (input.contains ("!")) // returns bool ... If you need to know the position, use String's indexOf method.
3rd Apr 2018, 10:20 AM
Tashi N
Tashi N - avatar
0
String str="The entered String"; if(str.indexOf('!')==-1) System.out.print("Does not contain exclamation");
3rd Apr 2018, 11:51 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
0
I've finally got that working so thanks but now I am running into an issue where the program will repeadatly show the error message, rather than reverting back to previous step/asking for another input. Any help?
6th Apr 2018, 12:01 PM
Jokitsa
Jokitsa - avatar
0
What kind of exception is being thrown?
6th Apr 2018, 12:02 PM
Justin Hinkle
Justin Hinkle - avatar
0
Oh, my bad. You're saying it's displaying your error message. Could you send your while loop?
6th Apr 2018, 12:04 PM
Justin Hinkle
Justin Hinkle - avatar
0
Thanks for the quick reply Justin. Here's my code so far; https://code.sololearn.com/creVdUFUfu3m As you can see I am having issues with not only while loops, but also finding values of strings from user input (check lines 19 & 20).
6th Apr 2018, 12:24 PM
Jokitsa
Jokitsa - avatar
0
Jokitsa, line 14 needs to be in your while loop in order to continue promoting for input. Currently your input continues to show error message because there is no way for it to break from the loop! Try something like this: getInput; While(invalidInput){ showError; getInput; } This is dummy code but I hope you get the idea!
6th Apr 2018, 12:33 PM
Justin Hinkle
Justin Hinkle - avatar