I'm fairly new to Java, and I was making a small application that takes two cars and returns who is faster. I made another class for the cars. First I made all the objects in the main method and it worked, then I tried putting the code in another method and called that from main, just to make it neater, and I got an error. Probably something obvious, but I'm too tired to think straight.
Error:(7, 14) java: cannot find symbol
symbol: variable ferrari
location: class Test
Error:(7, 23) java: cannot find symbol
symbol: variable lamborghini
location: class Test
public class Test {
public static void main(String[] args) {
createCars();
race(ferrari, lamborghini);
}
public static void createCars() {
Car ferrari = new Car("Ferrari", "California");
ferrari.setHp(552);
ferrari.setAcceleration(3.3);
Car lamborghini = new Car("Lamborghini", "Huracan");
lamborghini.setHp(602);
lamborghini.setAcceleration(2.5);
Car bmw = new Car("BMW", "M5");
bmw.setHp(560);
bmw.setAcceleration(3.7);
Car cadillac = new Car("Cadillac", "CTS-V");
cadillac.setHp(640);
cadillac.setAcceleration(3.6);
}
public static void race(Car carA, Car carB) {
if (carA.getAcceleration() < carB.getAcceleration()) {
System.out.println("The " + carA.getMake() + " " + carA.getModel() + " is faster than the " + carB.getMake() + " " + carB.getModel());
} else if (carB.getAcceleration() < carA.getAcceleration()) {
System.out.println("The " + carB.getMake() + " " + carB.getModel() + " is faster than the " + carA.getMake() + " " + carA.getModel());
} else {
System.out.println("It's a tie");
}
}
}
You get that error because your car instances ferrari and lamborghini are not in the scope of the main function.
You may modify your create cars method to it returns a new car insteand:
public static Car createCar(String make, String model, int hp, double acceleration ) {
Car car = new Car(make, model);
car.setHp(hp);
car.setAcceleration(acceleration);
return car;
}
and then you can use it:
public static void main(String[] args) {
Car ferrari = createCar("Ferrari", "California", 552, 3.3 );
Car lamborghini = createCar("Lamborghini", "Huracan", 602, 2.5 );
race(ferrari, lamborghini);
}
... or directly
public static void main(String[] args) {
race(
createCar("Ferrari", "California", 552, 3.3 ),
createCar("Lamborghini", "Huracan", 602, 2.5 )
);
}
The objects that you create become unreachable (and therefore ready for garbage collection) as soon as the method in which you created them is over. This is because you assign them to local variables inside that method, and no other part of your program has access to these variables.
You need a way for the rest of your program to access the cars you created. One way is to make an object that "holds" them, like this:
class Garage {
private Car ferrari;
private Car lamborghini;
private Car bmw;
private Car cadillac;
// You could use a constructor instead of using a separate method.
public void createCars() {
ferrari = new Car("Ferrari", "California");
ferrari.setHp(552);
ferrari.setAcceleration(3.3);
lamborghini = new Car("Lamborghini", "Huracan");
lamborghini.setHp(602);
lamborghini.setAcceleration(2.5);
bmw = new Car("BMW", "M5");
bmw.setHp(560);
bmw.setAcceleration(3.7);
cadillac = new Car("Cadillac", "CTS-V");
cadillac.setHp(640);
cadillac.setAcceleration(3.6);
}
public void getFerrari() {return ferrari;}
public void getLamborghini() {return lamborghini;}
public void getBmw() {return bmw;}
public void getCadillac() {return cadillac;}
}
Now you can use the Garage class in your main() method, like this:
public static void main(String[] args) {
Garage garage = new Garage();
// If you move createCars into Garage's constructor, you wouldn't need to call createCars any longer.
garage.createCars();
race(garage.getFerrari(), garage.GetLamborghini());
}
Declare your objects ahead of time. This allows the variables to remain in scope for your race() function. Otherwise, only the createCars() method sees your Cars.
public class Test {
static Car ferrari;
static Car lamborghini;
static Car bmw;
static Car cadillac;
public static void main(String[] args) {
createCars();
race(ferrari, lamborghini);
}
public static void createCars() {
ferrari = new Car("Ferrari", "California");
ferrari.setHp(552);
ferrari.setAcceleration(3.3);
lamborghini = new Car("Lamborghini", "Huracan");
lamborghini.setHp(602);
lamborghini.setAcceleration(2.5);
bmw = new Car("BMW", "M5");
bmw.setHp(560);
bmw.setAcceleration(3.7);
cadillac = new Car("Cadillac", "CTS-V");
cadillac.setHp(640);
cadillac.setAcceleration(3.6);
}
}
Related
so I have this array in a class called Park:
private Product[] stock = new Product[MAX_PROD];
In another class called Test(I have Park extended to test), I have these elements that I trying to add to the array, but it never works. This is how it looks:
These are the variables for sedan "public Sedan(double price, int quantity, String make, String model, int year, String
color)"
public class AutoParkInventoryTestProgram {
public static void main(String[] args) {
AutoPark park1 = createPark1();
System.out.println(park1.getName() + "'s Stock Is:");
park1.displayAllProducts();
System.out.println();
}
public static AutoPark createPark1() {
AutoPark park1 = new AutoPark("Carleton AutoPark");
Sedan s1 = new Sedan(100, 10, "Ford", "Model-1", 2018, "White");
Sedan s2 = new Sedan(200, 10, "Honda", "Model-2", 2019, "Red");
park1.addProduct(s1);
park1.addProduct(s2);
return park1;
Sedan is a different class btw.
This is one of the red errors I get before I run my code:
Required type:
Product
Provided:
Sedan
Sorry for the lack of information I gave initially, this is how addProduct looks:
public boolean addProduct(Product p) {
if (currentStock < MAX_PROD - 1) {
stock[currentStock++] = p;
return true;
}
return false;
}
This is a theoretical question for practice.
The question is
Create an immutable class Car.
Create some instances of car to fill an Arraylist<Car> inside a Garage class.
The MyGarage class implements these methods from Garage:
getCar(String reg) – search for the car with registration number reg.
getMake(String make) – returns a list of cars that match the given make.
totalValue() – calculates the total value of all cars in the list.
changeOwner(String reg, String ow) – change the owner of car that has registration number reg to ow.
I do not understand the changeOwner method as it is not suppose to be able to change a instances of a immutable class I thought???
This is what I have done to work around it but just seems silly
import java.util.ArrayList;
public class MyGarage implements Garage {
private ArrayList<Car> myGarage;
public MyGarage() {
myGarage = new ArrayList<Car>();
}
#Override
//Adds a Car if the registration is unique
public boolean add(Car c) {
for(Car car : myGarage) {
if(car.getRegistration().equals(c.getRegistration())) {
System.out.println("Car has the same Registration as another illegal");
return false;
}
}
myGarage.add(new Car(c.getOwner(),c.getRegistration(),c.getMake(),c.getkilometres(), c.getprice()));
return true;
}
#Override
public Car getCar(String carID) {
for(Car car : myGarage) {
if(carID.equals(car.getRegistration())) {
System.out.println("Car Found");
return car;
}
}
System.out.println("No car of that record");
return null;
}
#Override
public ArrayList<Car> getMake(String make) {
ArrayList<Car> carModel = new ArrayList<Car>();
for(Car car : myGarage) {
if (car.getMake().equals(make)) {
carModel.add(car);
}
}
System.out.println(carModel.toString());
return carModel;
}
#Override
public void totalValue() {
double amount = 0;
for(Car car : myGarage) {
amount = car.getprice() + amount;
}
System.out.println("The total amount is: " + amount);
}
#Override
public boolean changeOwner(String registration, String ow) {
for(Car car : myGarage) {
if(car.getRegistration().equals(registration)) {
myGarage.remove(car);
car = new Car(ow, "444","F-50", 4, 4000.99);
myGarage.add(car);
return true;
}
}
return false;
}
}
In object-oriented and functional programming, an immutable object
(unchangeable object) is an object whose state cannot be modified
after it is created. This is in contrast to a mutable object
(changeable object), which can be modified after it is created. In
some cases, an object is considered immutable even if some internally
used attributes change, but the object's state appears unchanging from
an external point of view. - WikiPedia
Immutable objects are thus instances whose state doesn’t change after they have been initialized. These types of classes are generally good for applications that need to implement some form of caching and where you are worried about thread-safety in a multi-threaded environment (immutable objects are inherently thread-safe).
I don't see your Car class, but assuming it'll look something like this:
public final class Car {
final String registration;
final String owner;
public Car(String registration, String owner) {
this.registration = registration;
this.owner= owner;
}
public String getRegistration() {
return registration;
}
public String getOwner() {
return owner;
}
}
... notice that there are no setter methods in this class. Hence a car can only be initialized (i.e Car myCar = new Car("abcd", "John"); and the variables in them (namely, registration and owner) can never be updated.
So your changeOwner method is essentially looping through the instances of car in your garage and when it finds a matching registration number it removes that instance of car from your garage and then adds a whole new one.
To demonstrate this, you can run the following:
public class Garage {
public static void main(String ... args) {
List<Car> myGarage = new ArrayList<>();
myGarage.add(new Car("CG404GH", "John"));
System.out.println(myGarage);
for(Car car : myGarage) {
if("CG404GH".equals(car.getRegistration())) {
myGarage.remove(car);
Car updateCar = new Car("DD404GH", "John");
myGarage.add(updateCar);
}
}
System.out.println(myGarage);
}
}
This would print out something similar to the following (the portion after the # would be different on each run):
[Car#4411d970]
[Car#6442b0a6]
The important thing to notice here is that the value after the # are different, hence they are two completely different classes (instances) of car
I am new to JAVA and am attempting to call a method from a class that prints out a message using the same method within another class. I am very new to java and really want to learn.
What I want to do is call the getAllCustomerInfo() method from the CustomerInfo{} class which is being called from the Customer class. When I try to run the code I get the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field c
If I make c static (static Customer c = new Customer();) and try to run my code it only prints the commas out from the getAllCustomerInfo() method and not the getName(), getAddress etc information.
Any ideas? Thank you.
CLASS 1:
public class Customer {
//Assume I have getters and setters and fields
//Method I want to use in another class
public String getAllCustomerInfo() {
String message =
getName() + "\n" +
getAddress() + "\n" +
getAge();
System.out.println(message);
return message;
}
} //END OF CUSTOMER CLASS
CLASS2:
//Class I am trying to call method from
public class CustomerInfo {
Customer c = new Customer();
public static void main(String args[]) {
//Code where I am trying to access the method from the Customer class
while (choice.equalsIgnoreCase("y")) {
System.out.print("Enter a customer number: ");
int customerNumber = sc.nextInt();
String customerInformation = sc.nextLine();
// get the Product object
Customer customer = CustomerDB.getCustomer(customerNumber);
//Check if customer exits in DB
if (customerNumber == 1) {
// display the output
System.out.println(c.getAllCustomerInfo());
} else {
System.out.println("There is no one like that in the DB.");
}
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
In the CustomerInfo class, c is a instance variable which will not exist without an object instance of CustomerInfo class. Since you are referring it from static context you will get such error. You have to make c variable static or move it inside the main method.
public class CustomerInfo{
static Customer c = new Customer();
public static void main(String args[]) {
// your implementation
}
}
OR
public class CustomerInfo{
public static void main(String args[]) {
Customer c = new Customer();
// your implementation
}
}
I havent touched java in awhile. I need some help, what I am trying to do with this program is get the car class to calculate the carbonfootprint inside of the getcarbonfootprint() method. HOWEVER, like all the videos that I have been going through, I DON'T want to pass it back to the main class through a return value. Instead, I want to use the same variables in the class car through methods. I tried using the this value, however, that doesn't work either. If you can link me to the right location on this question, that will work as well.
MAIN CLASS:
package carbonfootprinttest;
public class CarbonFootprinttest {
public static void main(String[] args) {
building house = new building();
car fusion = new car();
bike trek = new bike();
double mytest = fusion.returncarbonfootprint();
System.out.print(mytest);
}
}
CAR CLASS:
public class car implements carbonfootprint {
private double mpg = 25;
public double yearly = 500;
public double carbonfootprint;
public void setmpg(){
System.out.println("The mpg of a ford fusion is " + mpg + " MPG.");
}
#Override
public void getcarbonfootprint() {
carbonfootprint = (yearly * mpg)/9;
}
public double returncarbonfootprint(){
System.out.println(carbonfootprint);
return carbonfootprint;
}
}
package carbonfootprinttest;
public class CarbonFootprinttest {
public static void main(String[] args) {
building house = new building();
car fusion = new car();
bike trek = new bike();
fusion.getcarbonfootprint();
double mytest = fusion.returncarbonfootprint();
System.out.print(mytest);
}
Need to call your method getcarbonfootprint() before returncarbonfootprint()
You should call getcarbonfootprint() first, it will generate and set value to variable carbonfootprint and then call returncarbonfootprint() to get updated value.
fusion.getcarbonfootprint();//Add this line of code in main method
double mytest = fusion.returncarbonfootprint();
I am learning Java and so, I want easy and understandable answer.
You will know what I mean when you see the code below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser = new Playeri();
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Suppose input is: John.
Then, output will be:
Your name is John.
Hey, bro! Are you null?
Here, I want John instead of null in output(line 2).
But I can't.
How can I access the same input to other classes (for e.g: Enemyu) other then the class having the declararion of the variable in which input is set (for e.g: Playeri)?
In Other Words:
How can multiple classes access the same value of variable that is set in a class through main method?
Please answer my question!
Thank you very much!
EDIT: Sorry for incorrect indentation in the code.
You are not setting value to the object's name variable.
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
Enemyu.enemUser.name=name; // Set it like this
}
}
class Enemyu {
static Playeri enemUser = new Playeri(); // make it static
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Output -
John
Your name is John.
Hey, bro! Are you John?
This solves your problem, but It is recommended you use setter-getter method.
You can pass it as a parameter to that method.
void showName(String myName) {
System.out.println("Your name is " + myName + ".");
}
and
enem.showUserName(user.name);
or, you could set it the way you did with the user class.
or, you could use mutators (setters/getters) in this case, a set-method, or pass it as a parameter to the constructor of the class.
Here is a fixed version of your code. The problem that you had was that you created two separate instances of Playeri and only set the name on one of the instances. This solution only creates a single instance of Playeri, thus bypassing the problem.
import java.util.Scanner;
public class Foo {
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu(user);
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser;
public Enemyu( Playeri p ) {
this.enemUser = p;
}
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
In your Enemyu class create getters and setters for your field variables.
Inside Enemeyu...
private String name;
...
public void setName(String newName) {
this.name = newName;
}
public String getName() {
return this.name;
}
...
Then inside your main method...
...
Enemyu enem = new Enemyu();
enem.setName("John");
Granted you might also want to provide your class with an overidden toString() method (which in your case is your showName). However, in your case; I don't think that will be necessary.
Your problem was that you were never setting the name field in the object.