1

I am having problems with an if statement error. Here's the code:

if (!firstGrade.matches("A+|A|A-|B+|B|B-|C+|C|C-|D+|D|D-|F") || !firstHonors.matches("n|h|ap")) {
        System.out.println("Invalid");
        System.exit(1);
}

The if statement is checking if firstGrade is not equal to a bunch of values, and if firstHonors is not equal to n, h, and ap. There is no problems wit the second part, it is only the firstGrade check that is causing problems.

The problem occurs when I try to enter a value with a plus sign (A+, B+, C+ etc.), it finds it invalid and exits the program. However, according to the code this should not be the case.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user
  • 43
  • 3

2 Answers2

3

+ and - have special meaning in regex so to actually look for them as part of your pattern, you need to escape them like so: \\+

See here

Community
  • 1
  • 1
John3136
  • 28,809
  • 4
  • 51
  • 69
  • This doesn't work. If I do this: `"A\+"` it says illegal escape character – user Oct 12 '15 at 23:32
  • 1
    @user Within a String literal, ``\`` is a special escape character. – Sotirios Delimanolis Oct 12 '15 at 23:33
  • Thanks, I edited the answer and I will mark it as "answered" as soon as it lets me. – user Oct 12 '15 at 23:36
  • `-` is only special within a character class since it may work as a range on `[a-z]`, however it isn't special if you write `[az-]`. Likewise, `-` is not special if you write `a-z`, since this will match that literal string – Federico Piazza Oct 12 '15 at 23:57
2

You need to escape the plus symbols, which means "one or more" in regex. Also, you can abbreviate your expression:

if (!firstGrade.matches("[ABCD][+-]?|F") || !firstHonors.matches("n|h|ap")) {

You'll note that I didn't escape the plus or minus, because when in a character class you don't need to for these characters (special case when minus is last it doesn't need escaping).

The expression [ABCD] is a character class, and means "any single character of A, B, C or D". '[+-]? means "zero or one of either + or -.


Your other expression may be shortened too (thanks to @Federico for suggesting):

if (!firstGrade.matches("[ABCD][+-]?|F") || !firstHonors.matches("[nh]|ap")) {
Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722