Passing variables in the same class between methods? - java

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();

Related

Instantiate objects using a helper class

I want to create an instance of my object, car. The problem I have is that i can create an instance of the car object such as, Car car1 = new car("Audi","A4","BF10YMR"); however I want to create car objects through a helper class. How do I call this helper class in main so that is of type car and not of type carHelper?
The car object requires a random registration number to be created and this is created in the carHelper class. The object is returned.
public class Car implements Comparable<Car>
{
public class Car
{
private String make;
private String model;
private String registration;
public Car(String make, String model, String reg)
{
this.make= make;
this.model= model;
registration = reg;
}
}
public class carHelper
{
public car genCar()
{
String reg = //some method to generate random registration.
String Make = //some method to randomly pick make from a list
String model = //some method to randomly pick model from a list
return new Car(make,model,registration);
}
}
public class Garage
{
public static void main (String args[])
{
Garage MyGarage = new Garage();
Car car1 = new Car("Audi","A4","BF10YMR") //works, but doesn't use helper
Car car2 = carHelper.genCar(); // something like this?
carHelper c = new carHelper(); // thought something like this but
System.out.println(c.genCar()); // creates object of type carHelper
// not car.
MyGarage.add(car1);
MyGarage.add(car2); // gives me carHelper cannot be converted to Car
}
}
public class GarageOp implements CarList
{
public GarageOp()
{
list = new ArrayList<Car>();
}
public boolean add(Car car)
{
if (list.contains(car) == false)
{
list.add(car);
return true;
}
}
}
Expected result is create car object using the helper class and add it to an ArrayList.
You could create this lists in the CarHelper and than, randomly, select the values and create a new Car with them. The UUID creates a random 128 bits (including hex) number and converts to a String
public class CarHelper {
private List<String> makeList = Arrays.asList("s", "t", "f", "n");
private List<String> modelList = Arrays.asList("yyt", "32g", "dc3", "aas");
public Car genCar() {
String reg = UUID.randomUUID().toString();
String make = makeList.get(new Random().nextInt(makeList.size() - 1));
String model = modelList.get(new Random().nextInt(modelList.size() - 1));
return new Car(make,model,reg);
}
}
Make the genCar() method as Static in the CarHelper class.
public car static genCar(){
// do stuff to create object
}
a non-static method can access a static variable or call a static method in Java.

Accessing particular, the same instance of an object from different java classes

I have 4 different classes: Main, Employee, Company and HRDepartment
Class Company stores employees, new instances of Employees are created in this class
John Doe instance was created in Company class
How to access this particular instance in other classes to change its fields/invoke methods
Please find code below. Thank you.
public class Main
{
public static void main(String[] args)
{
HRDepartment hr = new HRDepartment();
hr.payRenumeration(5000);
// how to print cash of John Doe? I can't type System.out.println(john_doe.getCash())
// because this instance was created in another class
}
}
public class Employee
{
private double cash;
public void addCash(double cash)
{
this.cash += cash;
}
public double getCash()
{
return cash;
}
}
public class Company
{
// New employee is created in Company system
Employee john_doe = new Employee();
}
public class HRDepartment
{
public void payRenumeration(double renumerationToPay)
{
// how to access instance john_doe created in Company class?
// if this was in the same class I could type simply john_doe.addCash(renumerationToPay);
}
}

How to set and get with three Classes?

I have a similar question on this topic but I dumbed it down and left out all the extra code. Also, I took the advice of the old question and set my variables to zero but it didn't make any difference.
Main:
public class WhyAPrints0Main {
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
WhyAPrints01 get = new WhyAPrints01();
set.setWhy(x);
get.print();
}
}
Class 1
public class WhyAPrints0 {
private int why;
public int getWhy() {
return why;
}
public void setWhy(int why) {
this.why = why;
}
}
Class 2
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
I really don't understand why this doesn't print 24 so if someone could explain well and possibly fix the code to where it does I would really appreciate it.
Why would you expect it to print 24?
You invoke the print() method:
get.print();
Which prints 0:
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
(Since 0 is the default value for an int, which is what is returned by get.getWhy().)
I think your confusion is coming from the concept of having multiple instances of the same class. You have two different instances of WhyAPrints0. One in your main() method and one in your second class. These two instances have nothing to do with one another. Setting a value in one doesn't affect the other.
As an analogy, consider two identical cars. If you put something in the trunk of one car, you shouldn't expect to retrieve it from the trunk of the other car. It doesn't matter that the cars are otherwise identical, they're not the same car.
You have to link your WhyAPrints01 to your WhyAPrints0 some how. Right now you have 2 instances of WhyAPrints0. You can change your WhyAPrints01 to something like this so you can set an instance of WHyAPrints0 in your WhyAPrints01 class.
public class WhyAPrints01 {
WhyAPrints0 get;
int a = 0;
public WhyAPrints01(WhyAPrints0 get){
this.get = get;
}
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
And your main to:
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
set.setWhy(x);
WhyAPrints01 get = new WhyAPrints01(set);
get.print();
}

Use another function to create objects

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);
}
}

Static variable of superclass acting weird in subclass-creation

I'm working on a classic homework program and cannot for the life of me figure out why my static variable in the superclass reacts the way it does..
The program is a bankaccount where I have created a superclass, Account, and two subclasses, CreditAccount and SavingsAccount.
public abstract class Account {
private double balance;
private int accountId;
**private static int lastAssignedNumber = 1000;** <--- the static int
private String accountType;
public Account (double q_balance, String q_accountType)
{
balance = q_balance;
accountType = q_accountType;
**accountId = ++lastAssignedNumber; <------ counter for new accountId**
}
)
public class CreditAccount extends Account {
public CreditAccount(double balance)
{
super(balance, "Creditaccount");
}
}
public class SavingsAccount extends Account {
public SavingsAccount(double balance)
{
super(balance, "Savingsaccount");
}
}
Previously, without subclasses when Account was the only object, the counter worked beautifully. But now when I create some new objects of savingsaccount and creditaccounts the program acts really weird and returns accountnumbers as follows:
new SavingsAccount(0); // **1001**
new CreditAccount(0); // **1001**
new CreditAccount(0); // **1002**
new SavingsAccount(0); // **1003**
new CreditAccount(0); // **1002**
new CreditAccount(0); // **1004**
new SavingsAccount(0); // **1005**
What in gods name is happening?! What am I missing? Shouldn't the two subclasses provoke the same static variable 'lastAssignedNumber' and add to it accordingly??
Kindest regards // Gewra
There is nothing wrong with your code , given that you are creating accounts in single thread model.
Your following code is working absolutely fine:
abstract class Account
{
private double balance;
private int accountId;
private static int lastAssignedNumber = 1000;
private String accountType;
public Account (double q_balance, String q_accountType)
{
balance = q_balance;
accountType = q_accountType;
accountId = ++lastAssignedNumber;
}
public int getAccountID()
{
return accountId;
}
}
class CreditAccount extends Account
{
public CreditAccount(double balance)
{
super(balance, "Creditaccount");
}
}
class SavingsAccount extends Account
{
public SavingsAccount(double balance)
{
super(balance, "Savingsaccount");
}
}
public class AccountLedger
{
public static void main(String st[])
{
Account ac[] = new Account[7];
ac[0] = new SavingsAccount(0); //1001
ac[1] = new CreditAccount(0); //1002
ac[2] = new CreditAccount(0); //1003
ac[3] = new SavingsAccount(0); //1004
ac[4] = new CreditAccount(0); //1005
ac[5] = new CreditAccount(0); //1006
ac[6] = new SavingsAccount(0); //1007
for (int i = 0 ; i < ac.length ; i++)
{
System.out.println(ac[i].getAccountID());
}
}
}
The concepts of multi- and singlethreading are frankly completely new to me but I've tried making both an AtomicInteger and a volatile variable with the exactly same result. I guess it's my structure of the program that is fundamentaly wrong.
The construct is a BankLogic-class holding an ArrayList of Customer-objects. The Customer-objects hold an ArrayList of Account-objects. It doesn't matter where I put the AtomicInteger-object, even though I put it in the BankLogic-class and pass it through to the constructor, it still turns out the same results.
Guess I should just place the accounts-ArrayList in the BankLogic-class and run a method comparing personal-ids (adding a persId-variable to the account-class) instead?
It certainly doesn't feel like such an elegant solution but I see no other way.
Thanks for all the answers!

Categories

Resources