Why am i getting java.lang.illegalstateexception why i run my code yet it has no errors | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Why am i getting java.lang.illegalstateexception why i run my code yet it has no errors

Import java.util.regex.Matcher; Import java.util.regex.pattern; public class RegularExpressionDemo{ public static void main(String[]args){ String s="I will be home in 10 minutes"; Pattern p=Pattern.compile("\\bin\\b"); Matcher m=p.matcher(s); while(m.find()); System.out.println("pattern matches"+m.group()+"at"+m.start()); } }

11th Aug 2020, 9:48 PM
John
John - avatar
7 Answers
+ 7
The problem is your while loop. You need to use curly brackets. while(m.find()); If you use semicolon the loop has no body. Means you are calling m.group() and m.start() also when m.find() is not true. Here is a correct code: https://code.sololearn.com/ch2TqOpRcnXO/?ref=app
11th Aug 2020, 10:30 PM
Denise Roßberg
Denise Roßberg - avatar
+ 6
Hello John About the exception: "Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation." https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html So you need to control all your method calls.
11th Aug 2020, 10:24 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
group() throws IllegalStateException - "If no match has yet been attempted, or if the previous match operation failed"
12th Aug 2020, 12:03 AM
zemiak
+ 1
1st error: There shouldn't be a semi colon after youe while statement. 2nd error: Enclose the statements written after the while statement within curly brackets i.e. { } Your final while statement should look like this: while(m.find()) { System.out.println("pattern matches"+m.group()+"at"+m.start()) }
12th Aug 2020, 9:53 AM
Aditya Negi
Aditya Negi - avatar
0
I am using Eclipse to run my codes so when I fail to place a semi colon at the end of the loop it usually says that there is an error but after placing the semi colon there is no errors
12th Aug 2020, 3:37 AM
John
John - avatar
0
'while' is like 'if' and 'for': it will run the code in between {} if condition matches. while(numberOfUsers > 0) { //do stuff as long as //numberOfUsers is above zero } Placing ; after while will most likely make it check condition forever, resulting in some crash. At least it's easy to notice. I'll add code example where accidentally added ; won't crash the code, but make output wrong. EDIT: here it is: https://code.sololearn.com/cl1899qT2x5a/?ref=app
12th Aug 2020, 5:05 AM
BlazingMagpie
BlazingMagpie - avatar
0
Thank you
12th Aug 2020, 6:24 AM
John
John - avatar