Error; cannot find symbol; Symbol: variable super - java

I am working on 3 programs that contain the classes CarRental.java, LuxuryCarRental.java, and UseCarRental.java, On my LuxuryCarRental.java, I keep getting the error, Error; cannot find symbol; Symbol: variable super for the class, here is my program, I'm relatively new to Java, so please be detailed! Thanks in advance!
import java.text.DecimalFormat;
public class LuxuryCarRental extends CarRental{
private boolean chauffeur;
private double dailyChauffeurFee;
public LuxuryCarRental(String renterName, int renterZip, String sizeOfCar,int rentalDays, boolean chauffeur) {
super(renterName, renterZip, sizeOfCar, rentalDays);
this.chauffeur = chauffeur;
}
public void display(){
super.dailyRentalFee = 79.99;
this.dailyChauffeurFee = 0;
if(chauffeur){
this.dailyChauffeurFee = 200;
}
super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Car Rental - Renter Name : " + super.getRenterName() + ", Renter Zip: " + super.getRenterZip() +
", Rental Days : " + super.getRentalDays() +
", Daily Rental Fee: " + dailyRentalFee + ", Daily Chauffer Fee: " + dailyChauffeurFee +
", Total Rental Fee: " + df.format(totalRentalFee));
}
}
And here are all the classes from all three of my programs that correspond to each other.
public class CarRental {
private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;
public class UseCarRental
public class LuxuryCarRental extends CarRental {
private boolean chauffeur;
private double dailyChauffeurFee;
public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
renterName = renterName;
renterZip = renterZip;
sizeOfCar = sizeOfCar;
rentalDays = rentalDays;
And my altered code:
public class CarRental
{
public static void main(String[] args)
{
private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;
}
public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
renterName = renterName;
renterZip = renterZip;
sizeOfCar = sizeOfCar;
rentalDays = rentalDays;
}
public void setDailyRentalFee(double dailyRentalFee)
{
this.dailyRentalFee = dailyRentalFee;
}
public double getDailyRentalFee()
{
return dailyRentalFee;
}
public void display(){
if(sizeOfCar.equalsIgnoreCase("economy"))
{
dailyRentalFee = 29.99;
}
else if(sizeOfCar.equalsIgnoreCase("midsize"))
{
dailyRentalFee = 38.99;
} else {
dailyRentalFee = 43.50;
}
//calculates total rental fee
this.totalRentalFee = this.dailyRentalFee * rentalDays;
DecimalFormat df = new DecimalFormat("0.00");
//displays output
System.out.println("Car Rental - Renter Name : " + renterName + ", Renter Zip: " + renterZip +
", Size of car: " + sizeOfCar + ", Rental Days : " + rentalDays +
", Daily Rental Fee: " + dailyRentalFee + ", Total Rental Fee: " + df.format(totalRentalFee));
}
public String getRenterName()
{
return renterName;
}
public int getRenterZip()
{
return renterZip;
}
public int getRentalDays()
{
return rentalDays;
}
}

super.dailyRentalFee = 79.99;
This doesn't work. The same goes for every other place you've used it.
I assume your class has a private field dailyRentalFee?
Make it protected instead. Or use public/protected getters and setters.
You're in a subclass which you should really view as an extension of the superclass. Everything that is available in the superclass is available in the subclass, provided you don't use private access but rather protected (available in current class and subclass) or public (available everywhere that has access to the current class).
Example:
class SuperClass {
protected int someValue = 5;
private int anotherValue = 10;
}
class SubClass extends SuperClass {
public void doSomething() {
someValue = 6; // I can access it because it's protected instead of private
anotherValue = 1; // I can't access it because it's private and only accessible in the SuperClass
}
}
To summarize:
Drop the super.X, super() is used to call the constructor of the superclass
Use protected or public access identifiers instead of private

First thing, super doesn't work the way you have used it.
when you extend a class, CarRental in your case, you inherite all public and protected members of that class. so to use a variable of your super class, you dont have to prefix super, you can just use the variable as if the child class holds it. so instead of
super.dailyRentalFee = 79.99;
use
dailyRentalFee = 79.99; // since dailyRentalFee is protected in class CarRental
// this will work
similarly,
super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();
should be written as
totalRentalFee = dailyRentalFee * getRentalDays() + this.dailyChauffeurFee * getRentalDays();
provided, the method getRentalDays is public in the CarRental class.
and about the error you mentioned in #Jeroen's answers' comments,
make sure LuxuryCarRental and CarRental are in the same package. To be simple,
make sure both files are in the same folder.
EDIT:
Your code doesn't contain a main method, that is why that error is produced. You should have a main method in your program for it to execute. That is the starting point of all java applications. so define a class with a main method inside and then create a LuxuryCarRental object and perform your computations there. for example,
class Sample {
public static void main(String[] args) { //this is how all main methods would look
LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
//call the LuxuryCarRental methods as per your coding requirements
}
}
see, its simpe,
class CarRental {
//CarRental code
}
class LuxuryCarRental {
//LuxuryCarRental code
}
class Test {
public static void main(String[] args) {
LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
luxuryCar.display();
}
}

Related

java print arraylist of interface

I'm learning observer design pattern from one of youtube videos and want to understand a bit more the behavior of interface arraylist, I think I quite understand how it works but when it comes the interface arraylist, its confusing to me how to access the value inside loop.
the subject and observer interfaces as follow;
public interface Subject {
public void register(Observer o);
public void unregister(Observer o);
public void notifyObserver();
}
public interface Observer {
public void updateViaObserver(double ibmPrice, double aaplPrice, double googPrice);
}
package observer_pattern;
import java.util.ArrayList;
import java.util.Arrays;
public class StockGrabber implements Subject{
private ArrayList<Observer> observers;
private double ibmPrice;
private double aaplPrice;
private double googPrice;
public StockGrabber(){
// Creates an ArrayList to hold all observers
observers = new ArrayList<Observer>();
}
public void register(Observer newObserver) {
observers.add(newObserver);
}
public void notifyObserver() {
for(Observer observer : observers){
observer.updateViaObserver(ibmPrice, aaplPrice, googPrice);
}
}
public void setPrice(double newIBMPrice, double newAAPLPrice, double newGOOGPrice){
this.ibmPrice = newIBMPrice;
this.aaplPrice = newAAPLPrice;
this.googPrice = newGOOGPrice;
notifyObserver();
}
}
package observer_pattern;
public class StockObserver implements Observer {
private double ibmPrice;
private double aaplPrice;
private double googPrice;
private Subject stockGrabber;
public StockObserver(Subject stockGrabber){
this.stockGrabber = stockGrabber;
this.observerID = ++observerIDTracker;
stockGrabber.register(this);
}
// Called to update all observers
public void updateViaObserver(double ibmPrice, double aaplPrice, double googPrice) {
this.ibmPrice = ibmPrice;
this.aaplPrice = aaplPrice;
this.googPrice = googPrice;
// this works
printThePrices();
// doesn't work
toString();
}
public void printThePrices(){
System.out.println(observerID + "\nIBM: " + ibmPrice + "\nAAPL: " +
aaplPrice + "\nGOOG: " + googPrice + "\n");
}
public String toString() {
return "StockObserver: ibmPrice=" + ibmPrice + " aaplPrice=" + aaplPrice;
}
}
MAIN
package observer_pattern;
public class GrabStocks{
public static void main(String[] args){
StockGrabber stockGrabber = new StockGrabber();
StockObserver observer1 = new StockObserver(stockGrabber);
stockGrabber.setIBMPrice(197.00);
stockGrabber.setAAPLPrice(677.60);
stockGrabber.setGOOGPrice(676.40);
observer1.toString();
}
}
How to access value for my ArrayList<Observer> observers inside "notifyObserver" method? if I do this System.out.println(observers.get(0)); I get observer_pattern.StockObserver#446cdf90
How to access value for my ArrayList observers inside "notifyObserver" method?
You're already doing it.
public void notifyObserver() {
for(Observer observer : observers){
observer.updateViaObserver(ibmPrice, aaplPrice, googPrice);
}
}
if I do this System.out.println(observers.get(0)); I get observer_pattern.StockObserver#446cdf90
That's because your StockObserver class does not have a toString method that returns a human readable representation of the object. Something like this
public String toString() {
return "StockObserver: ibmPrice=" + ibmPrice + " aaplPrice=" + aaplPrice;
}

I am not sure why getCost(); is returning an error

I am currently working on a little project for school and i am not sure why this is causing an issue.
package tripcalculator;
import java.util.Scanner;
public class Trip {
Scanner kbd = new Scanner(System.in);
private int distance;
public final double MILEAGE = 0.14;
public final double COST_PER_LITRE = 1.29;
public void getLitresUsed() {
}
//constructor with distance parameter passed
public Trip(int distance) {
}
//default construtor
public Trip() {
System.out.println("Enter distance travelled: ");
distance = kbd.nextInt();
}
//getter and setter
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLitresUsed(int distance){
double litresUsed = MILEAGE * distance;
return litresUsed;
}
public double getCost(double litresUsed){
double cost = litresUsed * COST_PER_LITRE;
return cost;
}
public String toString(String litresUsed) {
getLitresUsed();
getCost();
String output = "Trip Details\n" + "\n" + "Distance: " + distance + " km\n" + "\n" + "Litres Used: " + litresUsed + "\n" + "\n" + "Cost: $" + cost;
return output;
}
}
as you see there is an issue with getCost and I am not sure why this is causing an issue. in my main I have the following code:
package tripcalculator;
public class TripCalculator {
public static void main(String[] args) {
Trip trip1 = new Trip();
trip1.getLitresUsed();
showTrip(trip1);
}
public static void showTrip(Trip trip1) {
System.out.println(trip1.toString());
}
}
This is a program that is used to calculate the total cost of the trip and i am not sure why it is not returning a value from getCost if anyone could explain this I would greatly appreciate such!
Jack!
I've refactored your program. Read it carefully and analyze my comments.
Trip.java:
package tripcalculator;
import java.util.Scanner;
public class Trip {
Scanner kbd = new Scanner(System.in);
private double distance; // This should be a double value
final double MILEAGE = 0.14; // Let;s make constants private also. They are not needed for the world.
final double COST_PER_LITRE = 1.29;
// public void getLitresUsed() { // What was the purpose of this? Removed.
//
// }
// constructor with distance parameter passed
// public Trip(int distance) { // Actually, this constructor does not do
// anything. Removed.
// }
// default constructor
public Trip() {
System.out.println("Enter distance travelled: ");
distance = kbd.nextInt();
}
// getter and setter
public double getDistance() {
return distance;
}
// public void setDistance(int distance) { // We do not need setter method as
// distance is being set when constructing Trip object.
// this.distance = distance;
// }
public double getLitresUsed() { // distance is class variable. No need in method parameter distance. Removed.
double litresUsed = MILEAGE * distance;
return litresUsed;
}
public double getCost() { // litresUsed is being calculated by method. So, parameters has been removed and
// changed to method output.
double cost = getLitresUsed() * COST_PER_LITRE;
return cost;
}
#Override // Actually, we're overriding method here. Be careful.
public String toString() {
// getLitresUsed(); // These methods' outputs have been moved to String
// generation.
// getCost();
String output = "Trip Details\n" + "\n" + "Distance: " + distance + " km\n" + "\n" + "Litres Used: "
+ getLitresUsed() + "\n" + "\n" + "Cost: $" + getCost();
return output;
}
}
TripCalculator.java:
package tripcalculator;
public class TripCalculator {
public static void main(String[] args) {
Trip trip1 = new Trip();
// trip1.getLitresUsed(); // No need in calling this method from outside.
showTrip(trip1);
}
public static void showTrip(Trip trip1) {
System.out.println(trip1.toString());
}
}
Good luck!

Need help finding the error

I have the following code which contains a run-time error. The code was meant to print out:
Vehicle mode:flight Fuel:propane Max Altitude:10000
Vehicle mode:traversal Fuel:coal Horsepower:5000
I could not find it myself (as I am fairly new to coding) and would like some help if possible.
Thanks.
class Main {
public static void main(String[] args) {
HotAirBalloon airbag = new HotAirBalloon(10000);
Locomotive loco = new Locomotive(5000);
System.out.println(airbag.toString());
System.out.println(loco.toString());
}
}
class Vehicle {
String mode, fuel;
public String toString() {
return "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
}
class HotAirBalloon extends Vehicle {
int maxAltitude;
HotAirBalloon(int _alt) {
mode = "flight";
fuel = "propane";
maxAltitude = _alt;
}
public String toString() {
return toString() + " Max Altitude:" + maxAltitude;
}
}
class Locomotive extends Vehicle {
int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;
}
public String toString() {
return toString() + " Horsepower:" + horsePower;
}
}
Because you are trying to call the super classes version of the current method you need to add super.toString()
//old
return toString() + " Horsepower:" + horsePower;
//new
return super.toString() + " Horsepower:" + horsePower;
You also need to do this with your other subclass
When you a method calls itself its called recursion, where a method keeps calling itself until a certain condition.
This code will do fine. the problem was that you were calling toString() multiple times which was causing a Stack overflow. plus you have to declare a String in parent class vehicle and update it in the child classes with flight mode etc..run the code below:
class Main {
public static void main(String[] args) {
HotAirBalloon airbag = new HotAirBalloon(10000);
Locomotive loco = new Locomotive(5000);
System.out.println(airbag.toString());
System.out.println(loco.toString());
}
}
class Vehicle {
String mode, fuel;
String s;
}
class HotAirBalloon extends Vehicle {
int maxAltitude;
HotAirBalloon(int _alt) {
mode = "flight";
fuel = "propane";
maxAltitude = _alt;
s= "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
public String toString() {
return s + " Max Altitude:" + maxAltitude;
}}
class Locomotive extends Vehicle {
int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;
s= "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
public String toString() {
return s+ " Horsepower:" + horsePower;
}
}

I need to add a power up option where I can determine the value and select which superhero to give the value to

Here is what I have so far so as you can see I made a class for the powerup but I just keep getting stuck over and over again and ended up getting frustrated cause I couldn't figure it out myself.
public class Superhero {
private int heroStr;
public int powerUp;
private String name;
public Superhero(String name, int heroStr) {
this.name = name;
this.heroStr = heroStr;
System.out.println(name + " Strength is " + heroStr);
}
public Superhero(String name) {
this.name = name;
heroStr = 10;
System.out.println(name + " Strength is " + heroStr);
}
public int getStr() {
return heroStr;
}
public int powerUp(int powerUp) {
}
public static void main (String[] args) {
Superhero Gambit = new Superhero("Gambit");
Superhero Groot = new Superhero("Groot", 79);
}
}
Here you are:
public void powerUp(int powerUp){
//this.powerUp is the powerUp in your class, the powerUp without "this" is the powerUp given to the method
this.powerUp+=powerUp;
}
All you need now is to change your powerUp method:
public void powerUp(int powerUp) {
this.heroStr += powerUp;
}
and since you instantiated the superheroes, all you need is to call their methods, ex:
public static void main(String args[]){
SuperHero gambit = new SuperHero("Gambit",10);
gambit.powerUp(10);
System.out.println(gambit.getStr()); //should be 20
}
Also, as a side note:
the correct naming convention for variable names is:
Class object = new Class();

JAVA: Creating new objects that don't interfere with other objects of same class

I'm new here (also new to programming) and I tried to look for an answer but couldn't come up with one. My assignment is due today so help would be very appreciated. This problem has happened to me twice, but the first I was able to ignore it by programming another way now I can't anymore. Every time I create a new object (Agent a = new Agent() <-- name of my class), it interferes with other objects of same type (does this have anything to do with reference types?). I'm trying to make a DiscussionDirector class that takes two Agent objects and creates a randomized conversation between them (Random based), but I can't even get started because I haven't been able to create two objects of type Agent yet.
Here's the code for Agent:
import java.util.Calendar;
import java.io.*;
import java.util.Random;
public class Agent{
private static boolean isMale;
private static String birthdate;
private static int birthyear;
private static int birthmonth;
private static int birthday;
private static String name;
private static String nativeCity;
private static String currentCity;
private static String major;
private static Random r = new Random();
public static void main(String[]args){
}
public String getCityNow(){
return this.currentCity;
}
public String getCityBorn(){
return this.nativeCity;
}
public String getName(){
return this.name;
}
public boolean getGender(){
return this.isMale;
}
public String getMajor(){
return this.major;
}
public String getBirthday(){
String birthdate = (this.birthday + "/" + this.birthmonth + "/" + this.birthyear);
return birthdate;
}
public void sayHelloTo(String name){
System.out.println(this.name + " says: Hi " + name + ", I'm " + this.name);
}
public void sayHello(){
System.out.println(this.name + " says: Hello, my name is " + this.name);
}
public void CityBorn(){
System.out.println(this.name + " says: I am from " + this.nativeCity);
}
public void howOldAreYou(){
System.out.print(this.name + " says: I am ");
if(Calendar.getInstance().get(Calendar.MONTH) < this.birthmonth){
System.out.println((Calendar.getInstance().get(Calendar.YEAR) - this.birthyear - 1) + " years old");
}
else if((Calendar.getInstance().get(Calendar.MONTH) == this.birthmonth) && (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == this.birthday)){
System.out.println((Calendar.getInstance().get(Calendar.YEAR) - this.birthyear - 1) + " years old");
}
else{
System.out.println((Calendar.getInstance().get(Calendar.YEAR) - this.birthyear) + " years old");
}
}
public void sayGender(){
System.out.println(this.name + " says: I am a ");
if(isMale == true){
System.out.print("man");
}
else{
System.out.print("woman");
}
}
public void CityNow(){
System.out.println(this.name + " says: I currently live in " + this.currentCity);
}
public void sayMajor(){
System.out.println(this.name + " says: I am studying " + this.major);
}
public void whoAreYou(){
sayHello();
CityBorn();
howOldAreYou();
sayMajor();
CityNow();
}
public Agent()throws IOException{
this.isMale = r.nextBoolean();
if(this.isMale == true){
WordList MaleNames = new WordList("MaleNames.txt");
this.name = MaleNames.getRandomWord();
}
else{
WordList FemaleNames = new WordList("FemaleNames.txt");
this.name = FemaleNames.getRandomWord();
}
this.birthyear = 1995 - r.nextInt(60); //Agents can't be too young or too old.
this.birthmonth = r.nextInt(11)+1;
if(this.birthmonth == 1|this.birthmonth == 3|this.birthmonth == 5|this.birthmonth == 7|this.birthmonth == 8|this.birthmonth == 10|this.birthmonth == 12){
this.birthday = r.nextInt(30)+1;
}
else if (this.birthmonth == 2){
this.birthday = r.nextInt(27)+1;
}
else{
this.birthday = r.nextInt(29)+1;
}
WordList Major = new WordList("Majors.txt");
this.major = Major.getRandomWord();
WordList Cities = new WordList("Cities.tx");
this.nativeCity = Cities.getRandomWord();
this.currentCity = Cities.getRandomWord();
}
public Agent generateAgent()throws IOException{
return new Agent();
}
}
So yeah, does anyone have any idea why when I create a two Agent() objects and then do generateAgent() objects on them, they're always the same?
Thanks
You've made all your class variables static, which means one copy for the whole class. Remove static on all of them, so they all have one value per object instance.
This is because all fields are declared static in your agent class.
A static field is shared among all instances of the class.
To solve your issue just remove the static keyword!
A typical use of static keyword inside a class is a counter of created instances of that class.
public class Agent{
private static int numberAgent;
private String birthdate;
private int birthyear;
private int birthmonth;
...
}
And in the constructors of the class, you do
numberAgent++;
As the static variable of a class are shared across all the instances of the class,
you will have the number of agents instanciated in all Agent objects.

Categories