+ 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.
8 Answers
+ 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!
+ 14
String input = ... // the user input
if (input.contains ("!")) // returns bool
...
If you need to know the position, use String's indexOf method.
0
String str="The entered String";
if(str.indexOf('!')==-1) System.out.print("Does not contain exclamation");
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?
0
What kind of exception is being thrown?
0
Oh, my bad. You're saying it's displaying your error message. Could you send your while loop?
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).
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!