-3

Doing some summer vacation exercises for Java, and I'm trying to verify social security (specific for my country)

Something doesn't add up for me with charAt(0) Given social security "300198", it prints "Error 1" at the moment.

public void authenticateCpr(Member member){
        if (member.getCpr().charAt(0) > 3) {
            System.out.println("Error 1");
        }
        if (member.getCpr().charAt(0) == 3 && member.getCpr().charAt(1) > 9){
            System.out.println("Error 2");
        }
    }

What am I missing? Happy summer Kind regards

Malthe22
  • 15
  • 8
  • 1
    Please step through your code with the debugger and look at the value of charAt(0). Have a think about it. – tgdavies Jul 06 '21 at 11:51
  • 1
    The return type for charAt is char not int. So you would have to change the char to int and then compare it. – Alien Jul 06 '21 at 11:51
  • 1
    If your intent is to check that "the first character is a number greater than 3", then you're doing it wrong. What you're doing, with that input, is exactly `if 51 > 3`, which is `true`, – ernest_k Jul 06 '21 at 11:52

1 Answers1

2

String.charAt(0) returns '3' which ASCII code equals to 51. You should write something like this

public void authenticateCpr(Member member){
        if (member.getCpr().charAt(0) > '3') {
            System.out.println("Error 1");
        }
        if (member.getCpr().charAt(0) == '3' && member.getCpr().charAt(1) > '9'){
            System.out.println("Error 2");
        }
    }
Semyon Kirekov
  • 1,237
  • 8
  • 20
  • 3
    Note that characters in Java are not 'ASCII', they are actually UTF-16. The numeric values are the same for the range 0 to 127, but it would be wise to get out of the habit of thinking that characters and ASCII are synonymous. This quibble doesn't change the correctness of the answer, though. – iggy Jul 06 '21 at 11:58