0

Why won’t this code throw an exception? Have tried a lot of things but when I test it with a JUnit class like this, for example, it won’t throw an exception:

Vehicle e = new Vehicle('C', 'G', "A1234");
// Constructor
public Vehicle(char kType, char dType, String regNr) {
    String temp0 = regNr.substring(0, 2);
    String temp = regNr.substring(2);
    boolean finish = false;

    if ("" + kType == "C") {
        for (char c : temp0.toCharArray()) {
            if (Character.isDigit(c)) {
                throw new IllegalArgumentException("3");
            }
        }

        if (temp.length() == 5) {
            finish = true;
        } else {
            finish = false;
            throw new IllegalArgumentException("4");
        }

        try {
            Integer.parseInt(temp);
        } catch (NumberFormatException nfe) {
            finish = false;
            throw new IllegalArgumentException("5");
        }
    }
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 3
    `if(""+kType=="C")`??? Why not just `if(kType=='C')`? – barak manos Feb 01 '17 at 07:20
  • @barakmanos In order to make the whole code pointless? – GhostCat Feb 01 '17 at 07:20
  • 1
    Besides: you want us to spend **our** time to help you. So **you** please spend the 1 minute it takes to properly format/indent your source code; instead of dumping this **mess** on us. – GhostCat Feb 01 '17 at 07:21
  • @GhostCat: I did not understand your comment/question. – barak manos Feb 01 '17 at 07:21
  • Just for the record: even when your question got closed as duplicate, you still can accept my answer if you find it helpful. And I think it is, as it definitely addresses your actual question ... – GhostCat Feb 01 '17 at 07:31

1 Answers1

1

It wouldn't.

if(""+kType=="C"){

that code will always give you false.

You (almost) never compare strings using ==; you have to use the equals() method. And then of course, when your if block is really entered, there are various conditions that can lead to throwing of those IllegalArgumentExceptions.

GhostCat
  • 137,827
  • 25
  • 176
  • 248