I have already looked at questions with exact same error code is mine , but i still wasnt able to resolve the problem by looking at the solutions under them. Currently i am trying to learn java through a tutorial , and by doing the exam same steps the code worked in the video but mine doesnt.
Car file ->
package com.ChiragAgg5k;
public class Car {
private int bmw;
public void setbmw(int bmw) {
this.bmw = bmw;
}
public int getbmw() {
return this.bmw;
}
public void main(String[] args) {
System.out.println(bmw);
}
}
Main file ->
public class Main {
public static void main(String[] args) {
Car carr = new Car();
carr.setbmw(20);
System.out.println(carr.getbmw());
}
}
Error code(s) ->
Error: Could not find or load main class Car
Caused by: java.lang.NoClassDefFoundError: com/ChiragAgg5k/Car (wrong name: Car)
Main.java:5: error: cannot find symbol
Car carr = new Car();
^
symbol: class Car
location: class Main
Main.java:5: error: cannot find symbol
Car carr = new Car();
^
symbol: class Car
location: class Main
I tried writing a simple hello world program in the package and it too gave error enter image description here
CodePudding user response:
Error Main.java:5: error: cannot find symbol
indicates missing import from other package or missing class in the same package
You have to add import statement for Car in your Main class. Because your Main class resides in another Package.
import com.ChiragAgg5k.Car;
public class Main {
public static void main(String[] args) {
Car carr = new Car();
carr.setbmw(20);
System.out.println(carr.getbmw());
}
}
As Alternative you could move Main into the same Package as Car class.
package com.ChiragAgg5k;
public class Main {
public static void main(String[] args) {
Car carr = new Car();
carr.setbmw(20);
System.out.println(carr.getbmw());
}
}
CodePudding user response:
So the solution was using Java code tester , instead of directly running the code in terminal as doing so does not change the path from which the code should actually be ran
Java code tester (a vs code extension) took care of it automatically