Eclipse says this:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The constructor Car(String, String, int) is undefined The
constructor Car(String, String, int) is undefined The method
getCarInfo() is undefined for the type Car The method getCarInfo() is
undefined for the type Car
at CarDriver.main(CarDriver.java:5)
and this is my driver:
public class CarDriver {
public static void main(String[] args) {
Car c1 = new Car("Nissan", "Z31", 175);
Car c2 = new Car("Honda", "Prelude", 145);
System.out.println(c1.getCarInfo());
System.out.println(c2.getCarInfo());
}
}
And this is my class:
public class Car {
/*
* Car class is a method to make a car with make and model of
* String and odometer of int to reflect how fast or how far
* the odometer reads, I guess.
*/
private String make;
private String model;
private int odometer;
public Car() { //This is the default constructor for the Car.
make = "Toyota";
model = "Supra"; //My favorite car, especially the 80s ones. (*•̀ᴗ•́*)و ̑̑
odometer = 225;
}
public Car(String make, String model, int odometer) {
this.make = make;
this.model = model;
this.odometer = odometer;
}
public void setMake(String manufacturer) {
this.make = manufacturer;
System.out.println("The car is made by" + this.make);
}
public void setModel(String type) {
this.model = type;
System.out.println("The car is a " + this.model);
}
public void setSpeed(int speed) {
this.odometer = speed;
System.out.println("The car goes " + this.odometer + " KPH");
}
public String getCarInfo() {
String carDescription = "The car is a " + model + " made by " + make + " and goes " + odometer + " KPH";
return carDescription;
}
}
Not really sure went wrong
Thanks for any help!
Your Eclipse might be confused. Sometimes IDEs get partial builds kind of stuck in memory and can't seem to clear them. I know this sounds like a cop-out, but have you tried tell Eclipse to clean, shutting down Eclipse completely, starting it up again, and tell it to do a full rebuild? I do this when things quit making sense. I've had to do it less since changing IDEs, but it still happens sometimes.
Oh, another possibility (unlikely, but possible): Could you maybe have a compiled earlier version of your classes in a place where Eclipse is picking it up as a library? If you're doing a mix of command-line work and Eclipse work, this could happen. Tell it to ignore any build directories not under its control, and check its imports for anything suspicious.
Related
First, I think the title of this post could be better, so if you want to edit it feel free to do so (or let me know how you think I should edit it).
I am going over practice problems for Java interviews. I am not interviewing right now, but I think this is the best way for me to find all my weak spots with Java. And before you say it, yes, I am finding I am VERY weak in many areas of Java and that I will need to do lots or review before interviewing.
I have some questions about the following code:
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle() { }
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
make = "Ford";
numWheels = 4;
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
make = "Kawasaki";
numWheels = 2;
this.model = model;
this.year = year;
}
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
First, I notice that there are no references to super() in the code. I thought that when you are dealing with super classes and subclasses, it was required that the subclass constructor include a reference to the super class constructor in the form of super(); (and including parameters if the super class constructor has them). Yet this code seems to work without them. Am I wrong about this requirement? Am I missing something else in this picture?
Second, the Kawasaki class doesn't include the decoration #Override for the countWheels() method. Since this method has the same name (albeit different parameters) as the super class' countWheels() method, wouldn't it be required to have an #Override decoration? Or is that only if the parameters are the same type and same order?
Thanks!
If you do not explicitly call super() in your derived class, the Java compiler will automatically generate a call to super() for you. But this, of course, only works if the base class constructor takes no arguments. This can be demonstrated by adding a System.out.println("Constructor called."); statement to your otherwise empty Vehicle constructor.
The #Override decorator, as you have found out but have not convinced yourself of, is optional. But it is considered a "best practice" to use this when overriding a method for catching errors if you change the method signature.
The one, hopefully constructive, comment I would make is that since a Vehicle must have attributes make and numWheels, I personally would require that these be specified in the Vehicle constructor. Now there is no possibility of having a derived class with these attributes undefined.
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle(String make, int numWheels) {
this.make = make;
this.numWheels = numWheels;
}
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
super("Ford", 4);
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
super("Kawasaki", 2);
this.model = model;
this.year = year;
}
#Override
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
I am trying to create a random car generator that also displays info. I thought I had everything until the randomCar portion. It says that
'com.company.Main.this' cannot be referenced from a static context
under the return statements in the switch. Any thought on to where I may be going wrong?
package com.company;
public class Main {
class Car{
private String name;
private boolean engine;
private int cylinders;
private int wheels;
public Car(String name){
this.name = name;
}
public String getName(){
return name;
}
public int getCylinders() {
if(cylinders == 0){
System.out.println("Unknown amount of cylinders");
}
return cylinders;
}
public int getWheels() {
return wheels;
}
public boolean isEngine() {
return engine;
}
}
class Tacoma extends Car{
public Tacoma(String name) {
super("Tacoma");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 6;
}
public int getWheels(int wheels) {
return 4;
}
}
class Motorcycle extends Car{
public Motorcycle(String name) {
super("Harley Davidson");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 2;
}
public int getWheels(int wheels) {
return 2;
}
}
class Volvo extends Car{
public Volvo(String name) {
super("Volvo");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 4;
}
public int getWheels(int wheels) {
return 4;
}
}
public static void main(String[] args) {
for (int i = 1; i<6; i++){
Car car = randomCar();
System.out.println("Car # " + i + ":" + car.getName() + "\n" +
"Number of cylinders: " + car.getCylinders() + "\n" +
"Number of wheels: " + car.getWheels()+ "\n" +
"Engine is: " + car.isEngine());
}
}
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
switch (randomNumber){
case 1:
return new Tacoma(); // This is where I am getting an error
case 2:
return new Motorcycle(); // This is where I am getting an error
case 3:
return new Volvo(); // This is where I am getting an error
}
return null;
}
}
I would start by reading here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html -> actually all the chapters there would be useful for you to read: https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Strictly speaking, to solve your "cannot be referenced from a static context" you can just make your classes static (Car, Tacoma, Motorcycle, Volvo) static class Car{
From my point of view you don't need nested classes, just create the classes in the same package as your Main class and you should be good to go (feel free to create more packages to better structure your classes)
Also I'm assuming your code is a work in progress because there are multiple issues with it:
methods like this don't make sense public boolean isEngine(boolean engine) {return true;} You receive a parameter that you ignore and you return a constant value: true; What I assume you want to do here is to have different types of cars each with its own predefined characteristics, but for that you should set the values for the attributes in the parent, Car. For this you either define protected setters, make the fields protected, or, best, create constructor which takes all the values
public Car(String name, boolean engine, int cylinders, int wheels) {
this.name = name;
this.engine = engine;
this.cylinders = cylinders;
this.wheels = wheels;
}
and you can have in Tacoma
public Tacoma(String name) {
super(name, true, 6, 4);
}
running your code I got the randomNumber 5 so that returned null and got a NPE, I assume work in progress
in your switch you are calling the default constructor new Tacoma() however that isn't available anymore since you defined a constructor with a parameter, use the available constructor or create the no-arg constructor.
There are other concerns regarding OOP principles so I recommend reading them again, just google "java OOP principles" and then "SOLID"... there are a lot of great resources out there, you just need time and patience and you'll get there!
When you put the Car class definition inside the class definition of Main, you made Car an inner class, so that a Car requires an outer class Main instance. In the static method there is no Main instance, and you can’t create the Car without it.
There is an immediate fix: add keyword static to the Car class:
static class Car {
which means there is no link to the enclosing object.
But there is no benefit here to making this a nested class, it would be better not to put one class definition inside another when you’re starting out.
The inner classes you've defined are instance members, meaning they belong to a specific instance of Main, and thus cannot be referenced from a static context that doesn't have a Main instance. The easiest way to resolve this would be to declare all the inner classes static.
First of all, to solve your error: 'com.company.Main.this' cannot be referenced from a static context, make all the methods static:
static class Car{//code here}
static class Volvo extends Car{//code here}
static class Tacoma extends Car{//code here}
static class Motorcycle extends Car{//code here}
Whenever you see that error, it means one static method is calling a non-static method. Therefore, just make both non-static or both static. The only exception is public static void main(String[] args); which must be static.
After solving the original errors, there is more to debug:
'Volvo(java.lang.String)' in 'com.company.Main.Volvo' cannot be applied to '()'
'Motorcycle(java.lang.String)' in 'com.company.Main.Motorcycle' cannot be applied to '()'
'Tacoma(java.lang.String)' in 'com.company.Main.Tacoma' cannot be applied to '()'
All this means is that your methods Tacoma(), Volvo(), and Motorcycle() require the parameter String name. So all you have to do is give them a name: here, it's
`new Tacoma("cool")`
new Volvo("car")
new Motorcycle("harley davidson")`
Finally, after solving the static and parameter problems, you are getting a NullPointerException, because randomCar() returns null. Your method says Car randomCar(), indicating it will return a Car, but then the return statement was return null;. Therefore, just return a Car - rtn here for our purposes:
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
Car rtn = null;
switch (randomNumber){
case 1:
rtn = new Tacoma("cool"); // This is where I am getting an error
case 2:
rtn = new Motorcycle("harley davidson"); // This is where I am getting an error
case 3:
rtn = new Volvo("car"); // This is where I am getting an error
}
return rtn;
}
This isn't all the debugging your code needs, but it's a start: here's what the system did so far:
Random number generated is: 3
Unknown amount of cylinders
Car # 1:Volvo
Number of cylinders: 0
Number of wheels: 0
Engine is: false
Random number generated is: 5
Hooray!
Did this help?
The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.
This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 9 years ago.
Sorry guys I am new to Java and I have an issue with my code. I have read through the threads and have seen many examples regarding this specific error (java.lang.NoSuchMethodError: main Exception in thread "main"). I just cant seem to wrap my head around where I would add (static void main(String[] args)) to the code. If you guys can point me in the right direction I would really appreciate it.
Here is what I have:
public class Employee {
String name;
String department;
double hourlyRate;
Employee(String name, String department, double hourlyRate) {
this.name = name;
this.department = department;
this.hourlyRate = hourlyRate;
}
public void setDepartment(String department) {
this.department = department;
}
public void setHourlyRate(double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public String getNameAndDepartment() {
return name + " " + department;
}
double weeklyPay(int numOfHourWorked) {
if (numOfHourWorked < 40) {
return (numOfHourWorked * hourlyRate);
} else
return (40 * hourlyRate);
}
}
class UnionEmployee extends Employee {
double dues;
UnionEmployee(String name, String department, double hourlyRate, double dues) {
super(name, department, hourlyRate);
this.dues = dues;
}
public void setDues(double dues) {
this.dues = dues;
}
double weeklyPay(int numOfHourWorked) {
if (numOfHourWorked <= 40) {
return (super.weeklyPay(numOfHourWorked));
} else
return ((super.weeklyPay(40) + ((numOfHourWorked - 40) * hourlyRate * 1.5)) - dues);
}
}
class CommissionEmployee extends Employee {
double commisionRate;
double salesAmount;
CommissionEmployee(String name, String department, double hourlyRate) {
super(name, department, hourlyRate);
}
public void setCommisionRate(double commisionRate) {
this.commisionRate = commisionRate;
}
public void setSalesAmount(double salesAmount) {
this.salesAmount = salesAmount;
}
double weeklyPay(int numOfHourWorked) {
return (super.weeklyPay(numOfHourWorked) + (commisionRate * salesAmount));
}
}
class TestEmployee {
UnionEmployee uEmp = new UnionEmployee(null, null, 0, 0);
CommissionEmployee cEmp = new CommissionEmployee(null, null, 0);
Employee emp = new Employee(null, null, 0);
void display(Employee emp, int numOfHourWorked) {
System.out.println("Name and department :" + emp.getNameAndDepartment ());
System.out.println("Weekly pay of employee :"
+ emp.weeklyPay(numOfHourWorked));
}
void display(UnionEmployee uEmp, CommissionEmployee cEmp,
int numOfHourWorked) {
System.out.println("Weekly Pay for UnionEmployee"
+ uEmp.weeklyPay(numOfHourWorked));
System.out.println("Weekly Pay for UnionEmployee"
+ cEmp.weeklyPay(numOfHourWorked));
}
}
OK so I started by separating each class into a different file. In looking through the Java tutorials it said to add static void main(String[] args) the way the tutorial had it setup was like this:
public class Misc {
static void main(String[] args) {
//body
}
}
So I did this:
class TestEmployee {
static void main(String[] args) {
UnionEmployee uEmp = new UnionEmployee(null, null, 0, 0);
CommissionEmployee cEmp = new CommissionEmployee(null, null, 0);
Employee emp = new Employee(null, null, 0);
void display(Employee emp, int numOfHourWorked) {
System.out.println("Name and department :" + emp.getNameAndDepartment ());
System.out.println("Weekly pay of employee :"
+ emp.weeklyPay(numOfHourWorked));
}
void display(UnionEmployee uEmp, CommissionEmployee cEmp,
int numOfHourWorked) {
System.out.println("Weekly Pay for UnionEmployee"
+ uEmp.weeklyPay(numOfHourWorked));
System.out.println("Weekly Pay for UnionEmployee"
+ cEmp.weeklyPay(numOfHourWorked));
}
}
}
Still get the same error : (java.lang.NoSuchMethodError: main Exception in thread "main").
OK I add public but now I get this:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
void is an invalid type for the variable display
Syntax error on token "(", ; expected
Duplicate local variable emp
Syntax error on token ",", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable display
Syntax error on token "(", ; expected
Duplicate local variable uEmp
Syntax error on token ",", ; expected
Duplicate local variable cEmp
Syntax error on token ",", ; expected
Duplicate local variable numOfHourWorked
Syntax error on token ")", ; expected
at TestEmployee.main(TestEmployee.java:9)
Your problem with main is that it doesn't exist, and you need to put one in your program for it to run. Put it in the main class, whichever one that is, but while it needs to be inside of the class, inside of the curly braces that define the class, you must also make sure that you don't put it inside of another method.
Above, I'd put it in TestEmployee.
I'd also take care to make sure every class above is declared public and is in its own file. So your code above which contains 4 classes, should be comprised of 4 files.
Edit
Also, be sure to declare your main method as a public method as #Aniket noted in comment below.
Edit 2
You're still not declaring main as a public method.
You have methods embedded within the main method. Remember that in Java you can't do this since all methods need to be class level. Get them out of the main method.
Your code indentation is horrible to say the least, and this will make it very difficult for you or us to see your coding problems. You will want to invest time and effort towards indenting your code properly. If you did this, you would see in an instant that you had methods inside of methods.
Based on a older question of mine Link I'm working on learning more about Casting and Instanceof. That is based upon a scenario described in a HeadFirst book
So basically I've now got a new class(Hybrid) that inherits from my Vehicle class what i'm trying to do is cast a Hybrid Object to display the extra information that comes with being a hybrid. It complies but doesn't really give me any idea what is causing the error except it just ends on the line i've marked.
public class ShowroomDriver {
public static void main(String[] args) {
Showroom cars = new Showroom("Cars");
Hybrid hybrid1 = new Hybrid("Toyota Prius", "Focus", "John Smith", "TOTAP453453987346283",
getCalendar(2,3,1998), getCalendar(24,2,2012),
"Right Hand",//Hybrid Only Info Edit: Forgot to commentout
true,
'C',
650, 82.0); //Cost & (Hybrid MPG)
cars.addVechicle(hybrid1);
cars.getVechicles();
Hybrid Class
import java.util.Calendar;
public class Hybrid extends Vehicle{
private double consumption;
private String drive;
public Hybrid(String Manufacture, String Model, String CustomerName, String Vin,
Calendar DateManufactured, Calendar Datesold, String Drive,
boolean HasbeenSold,
char TaxBand,
double Cost, double Consumption){
super(Manufacture, Model, CustomerName, Vin, DateManufactured, Datesold,
HasbeenSold,
TaxBand,
Cost);
this.consumption = Consumption;
this.drive = Drive;
}
public Double getConsumption() { return this.consumption; }
public String getDrive() { return this.drive; }
}
New Vehicle Method
public void displayDetails(){
for(int i = 0; i <cars.theVehicles.size(); i++){
if(this.cars.theVehicles.get(i) instanceof Hybrid){//Error here
Hybrid thehybrids = (Hybrid)this.cars.theVehicles.get(i);
System.out.println("Consumption: " + thehybrids.getConsumption()+ "\n" +
"Drive: " + thehybrids.getDrive());
}
}
}
Do you need to cast ? You've already overridden the displayDetails() method to display hybrid-specific info. So you should just be able to call this and the runtime will determine the correct method to call.