0

I am getting this problem in my 'Debug Console' in VS code:

Exception in thread "main" java.lang.NoSuchMethodError: Car.<init>(Ljava/lang/String;)V
    at CarTest2.main(CarTest2.java:23)

I was following an example from a book and it doesn't seem to work.

class Car {
    String colour;
    String gearType;
    int door;

    Car() {
        this("white", "auto", 4);
    }

    Car(String colour) {
        this(colour, "auto", 4);
    }
    Car(String colour, String gearType, int door) {
        this.colour = colour;
        this.gearType = gearType;
        this.door = door;
    }
}

class CarTest2 {
    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car("blue");

        System.out.println("c1.colour = " + c1.colour + ", c1.gearType = " + c1.gearType + ", c1.door = " + c1.door);
        System.out.println("c2.colour = " + c2.colour + ", c2.gearType = " + c2.gearType + ", c2.door = " + c2.door);
    }
}

Expected answer:

c1.colour = white, c1.gearType = "auto", c1.door = 4 c2.colour = blue, c2.gearType = "auto", c2.door = 4

Stultuske
  • 9,296
  • 1
  • 25
  • 37
Jahad
  • 21
  • 2
  • The code you've posted works for me. Are you sure you recompiled both classes? Please show exactly how you compiled and ran the code. – Jon Skeet Jul 04 '19 at 08:18
  • 3
    Whatever book you are using, get rid of it. Not making your class public, not making your variables private, ... – Stultuske Jul 04 '19 at 08:18
  • Can not reproduce: https://ideone.com/qEmxh5 – Ivaylo Strandjev Jul 04 '19 at 08:19
  • Clean your project and rebuild. It should work fine. – rghome Jul 04 '19 at 08:20
  • @Stultuske the book is for beginners of Java, it's just teaching the basics of Java...(I guess) – Jahad Jul 04 '19 at 08:21
  • I just used cmd to compile and run and it worked fine. What's wrong with the VS code? – Jahad Jul 04 '19 at 08:22
  • @LearKing Learn the basics in the proper way. Make it right first time. Follow the good code guidelines even if its a learning code. – Kris Jul 04 '19 at 08:22
  • @LearKing yes, but it teaches the basics wrong. It's harder to unlearn bad material compared to learning it correct from the start. – Stultuske Jul 04 '19 at 08:23
  • Well thats why its called learning! :-) . BTW, clean the VSCode project and execute, it should work. Softwares mess up some times. – Kris Jul 04 '19 at 08:24
  • The answers to https://stackoverflow.com/questions/35186/how-do-i-fix-a-nosuchmethoderror explain the (general) cause for this kind of problem. The specific problem is that you (or your IDE) are not recompiling your code properly. – Stephen C Jul 04 '19 at 08:37

0 Answers0