I’m trying to learn about regular expressions but am not doing so well after reading through the java tutorial.
This program is supposed to take an imput in the format:
a) add dd dd together
b) subtract 05 from 13
c) add 02 to 03
And return the dd (+ or -) dd = answer
The (wrong) way I set this up is to have the prog try to find either of the 3 matches, and continue to do so until the user inputs “bye.” If there isn’t a match it should just prompt the user for an input again.
Here’s my code! With exactly 100 errors. :/
If anyone can help me with the syntax, it’d really be appreciated!
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Calculator {
public static void main(String[] args){
Scanner imp = new Scanner(System.in);
System.out.println("yes> ");
String s = imp.nextLine();
if (s.equals("bye")) {
System.exit(0);
}
while (true) {
Pattern p = Pattern.compile(s); //compile string, check for formats
Matcher x = p.matcher(\badd\b\s\d\d\s\d\d\s\btogether\b); //format add 12 12 together
Matcher y = p.matcher(\bsubtract\b\s\d\d\s\d\d\s\bfrom\b); //format subtract 05 from 13
Matcjer z = p.matcher(\badd\b\s\d\d\s\bto\b\s\d\d); //format add 02 to 03
boolean b = p.matches;
boolean l = x.matches;
boolean i = y.matches;
boolean g = z.matches;
if (l.equals(true))
return (\d\d " + " \d\d " = " \d\d+\d\d);
else if (i.equals(true))
return (\d\d " + " \d\d " = " \d\d-\d\d);
else if (g.equals(true))
return (\d\d " + " \d\d " = " \d\d+\d\d);
}
}
}
ugh where to begin…
first off
Pattern.compile()is expecting the regex (the format strings) whilematcher()expects the string to test against@Samir has shown you what was wrong with the regexes in the code itself (I edited them a bit for more clarity)
l.matchesneeds()you cannot call methods on primitive boolean variables
if(b)is sufficient to test if it is true or notand to get specific submatches you need to use capturing groups
to concatenate strings together you can use
+to output something to the console System.out.println should be used not return
with the most obvious errors solved: