Java toString in class - java

I am getting an error of cannot find symbol in my code posted below. I am trying to initalise a sedan using it's class and have the toString function right after but nothing is working for me. Please help
class cars {
String make;
String model;
String color;
int year;
double price;
public String sedancClass(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1;
sedan1 = new sedanClass("Ford" , "Model-1" , "white" , 2015, 20000);
}
}

According to what you provided, I think this is what you are trying to do
class cars {
String make;
String model;
String color;
int year;
double price;
// parametised constructor
public cars (String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1; // declaring cars object by name sedan1
sedan1 = new cars("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using cars constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
}
}
Why we use #Override annotation source
Using #Override annotation while overriding a method is considered as a best practice for coding in java because of the following two advantages:
If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class.
It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.

Related

Different values for each subclass

I would like to create a school(Houses) with 4 subclasses that take a basic values from the superclass(color, logo etc, each subclass with different values) and keep track, each sub class to itself of the number of students and points.
I also want to grant the ability to add points only for instance of Houses directly.
This is the code:
public class Houses {
int students = 75;
String color;
String logo;
String Founder;
String Trait;
String name;
int points = 0;
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
points += x;
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
students += 1;
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}
if im making the students and point as static its working fine but of course it add up all the sub classes together.
the best idea is to declare the values students and points inside each subclass as static?
Thanks for your time!
Looks like a misuse of sub-classes. Unless each sub-class is going to have it's own unique functionality, then each set of data should be associated to an instance of a House. You'd then most likely want to use the Constructor to set this data.
House Class
public class House {
int students;
String name;
String color;
//Other class variables
public House(int students, String name, String color) {
this.students = students;
this.name = name;
this.color = color;
}
//Various methods
}
Main Class
public class HouseTest {
public static void main(String[] args) {
House gryffindor = new House(75, "Gryffindor", "Red");
House ravenclaw = new House(68, "Ravenclaw", "Blue");
}
}
However, if you really want to set this data using a sub-class you can make use of the House constuctor via the super keyword which calls the parent constructor. Using the House from my code above it would be:
Gryffindor Class
public class Gryffindor extends House {
public Gryffindor() {
super(75, "Gryffindor", "Red");
//Set value for anything unique to Gryffindor here after super keyword
}
//Gryffindor specific methods
}
I will use a singleton School class to keep a single state count of students and points throughout the program. So create a class with those values you want to keep a single state track of and make them the class fields.
A singleton is a class that is instantiated once in memory and have the object shared by all classes within the application. This single state object in memory hold single state data points.
public class School{
private int students = 75;
private int points = 0;
private static final School instance = new School();
private School() {}
public static School getInstance() { return instance; }
public synchronized void addStudent() {
students++;
}
public synchronized void addPoints(int x) {
points += x;
}
public synchronized int getStudents() { return students; }
public synchronized int getPoints() { return points; }
}
So your House class will look like:
public class Houses {
School school = School.getInstance();
int students = school.getStudents();
String color;
String logo;
String Founder;
String Trait;
String name;
int points = school.getPoints();
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
school.addPoints(x);
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
And your Gryffindor class
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
school.addStudent();
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}

How do I get an out a value from an ArrayList from the user typing it in?

The question the user would see it "Which car would you like?"
And I want to be able to call that specific car in the array list and have it print on one line.
I'm using an if statement so that the user types in certain letters and it will spit out the specific car from the array by itself.
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Nikolai", "Model S", 2017, 54999.90));
carList.add(new Car("Fourd", "Escapade", 2017, 31999.90));
carList.add(new Car("Chewie", "Corvette", 2017, 44989.90));
carList.add(new UsedCar("Hyonda", "RichardPryor", 2015, 14795.50, 35987.6));
carList.add(new UsedCar("GC", "Chirpus", 2013, 8500.00, 12345.00));
carList.add(new UsedCar("GC", "Witherell", 2016, 14450.00, 3500.3));
String userInput = "";
for (Car theList : carList) {
System.out.printf(theList.getMake() + "\t " + theList.getModel() + "\t " + theList.getYear() + "\t "+ "$" + theList.getPrice());
}
System.out.println("Which car would you like? (Please type the name)");
userInput = scnr.nextLine();
if (userInput.equalsIgnoreCase("ni")) {
System.out.println(carList.get(0));
} else if (userInput.equalsIgnoreCase("fo")) {
System.out.println(carList.get(1));
} else if (userInput.equalsIgnoreCase("ch")) {
System.out.println(carList.get(2));
} else if (userInput.equalsIgnoreCase("hy")) {
System.out.println(carList.get(3));
} else if (userInput.equalsIgnoreCase("qu")) {
System.out.println(carList.get(6));
if (userInput.equalsIgnoreCase("gc")) {
System.out.println("Chripus or Witherell?");
}
if (userInput.equalsIgnoreCase("chr")) {
System.out.println(carList.get(4));
} else
System.out.println(carList.get(5));
}
I expected the System.out.println(carList.get()) to print out the corresponding array list excatly when the for loop runs. (Which I know the for loop works...)
As mentioned by #Scary Wombat in the comments, if you really want to use ArrayList the easiest way is to implement/override the toString method. Since you say that the toString method currently only prints the name of the car, you can change it to something like this:
public String toString() {
return this.getMake() + "\t " + this.getModel() + "\t " + this.getYear() + "\t "+ "$" + this.getPrice();
}
To be even clearer, a full working Car might be the following:
import java.util.ArrayList;
import java.util.Scanner;
class Car {
private String make;
private String model;
private int year;
private double price;
public Car(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String getMake() {
return this.make;
}
public String getModel() {
return this.model;
}
public int getYear() {
return this.year;
}
public double getPrice() {
return this.price;
}
public String toString() {
return this.getMake() + "\t " + this.getModel() + "\t " + this.getYear() + "\t "+ "$" + this.getPrice();
}
public static void main(String[] args) {
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Nikolai", "Model S", 2017, 54999.90));
carList.add(new Car("Fourd", "Escapade", 2017, 31999.90));
carList.add(new Car("Chewie", "Corvette", 2017, 44989.90));
String userInput = "";
System.out.println("Which car would you like? (Please type the name)");
Scanner scnr = new Scanner(System.in);
userInput = scnr.nextLine();
if (userInput.equalsIgnoreCase("ni")) {
System.out.println(carList.get(0));
} else if (userInput.equalsIgnoreCase("fo")) {
System.out.println(carList.get(1));
} else if (userInput.equalsIgnoreCase("ch")) {
System.out.println(carList.get(2));
}
}
}
Assuming that UsedCar inherits from Car, you can also override the toString method in UsedCar to something like:
public String toString() {
return super().toString();
}
This toString method is necessary because otherwise you are just printing the Car object hashcode value when you get it from the ArrayList. By overriding the toString method, the java compiler will call your toString method and print the information encapsulated in the Car instead. Hope that this example helps to clear things up!

Java - adding to an inherited JOptionPane

Good evening all!
I think there's something I don't understand here about either inheritance or JOptionPane, but basically I want to figure out how to actually use a new JOptionPane in the LuxuryCarRental subclass.
Currently it displays 2 dialog boxes if the choice is "l", one box from the parent class and a new one I added in the subclass. Ideally I would want only one dialog box. I think this is something that I can do without JOptionPane but I would like to try to make it work with JOptionPane if possible.
My code:
CarRental.java (parent class)
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public void display()
{
JOptionPane.showMessageDialog(null, "Car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
LuxuryCarRental.java (subclass)
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, int rentalDays)
{
super(name, zipCode, size, rentalDays);
if (size.equals("l"))
{
this.setDailyFee(79.99);
String includeChauffeur;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur.equals("Y") || includeChauffeur.equals("y"))
{
this.setDailyFee(279.99);
this.setTotalFee(this.getDailyFee()*this.getRentalDays());
JOptionPane.showMessageDialog(null, "Chauffeur # $200/day = $" + 200 * this.getRentalDays());
}
}
}
}
UserCarRental.java (driver class)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"));
CarRental userInfo = new LuxuryCarRental(name, zip, size, days);
userInfo.display();
}
}
Any help would be greatly appreciated!
I think that the lesson here is to not mix UI code with model code. Understand that your CarRental class and all of its subclasses are logical or model classes, and can be thought of here as classes that model a physical or logical reality. They should be used in this capacity, and should be written so information can be passed into them and extracted out of them, but they should not interact directly with the user. Instead that is the responsibility of the UI (user interface) classes, of which here it is quite simple and only your main method. So I suggest that you get your JOptionPane calls out of both CarRental and LuxeryCarRental, and instead display the JOptionPane in your main method after extracting state from your CarRental object.
Otherwise, if you absolutely must have the model classes display their information, then do it in a method that can be fully overridden. In fact you would have your child class override the display() method, and then print out its data there.

Is there any way to retrieve an input value from the past

I'm a beginner in java and it is my only code I know how to use so far. I'm working on a food system for an RPG game. Basically it displays a list of the available food items and ask you to press number to eat . After pressing a number, it prints out what you have decided to eat based on what your number corresponded to. I then need to retrieve what "food" you ate so that I can use it's stats. Here's what I have so far:
public String eatmenu() {
System.out.print ( "Consumables: ");
for ( Sustenance consum : consumables ) {
System.out.print ( "[" + consum + "], " );
}
int number = consumables.size();
int counter = 1;
while ( counter <= number ){
System.out.print ("\nPress " + counter + " to consume " + consumables.get(counter-1));
counter++;
}
int choice = reader.nextInt();
String eatchoice = "You decided to consume " + consumables.get(choice-1);
return eatchoice;
}
public String eat3(){
//the food just eaten,
}
Heres the code for the Food Class or "Sustenance":
public class Sustenance extends Item {
String n;
int v;
int s;
public Sustenance ( String name, int Nvalue, int size ){
n= name;
Nvalue = v;
size = s;
}
public String toString() {
String str = "The " + n + "increased your Nutrition level by " + v + ".\nYour backpack is also " +
s + " pounds lighter.";
return str;
}
}
Any ideas are appreciated as to what to put for the eat3 method. I know I will be using the toString method in order to print out the effects of eating the specific item but how do I refer to the item I just ate? I will take everything as critique. Thank you for your time.
Use JavaBeans to set the food and then get it. For example:
public class FoodBean{
public FoodBean(){}
private String foodName;
// other fields which you wana set or get
public void setFoodName(String foodName){
this.foodName = foodName;
}
public String getFoodName(){
return this.foodName;
}
// override the toString() if you want the object to represent the foodName stored
#Override
public String toString(){
return this.foodName;
}
}
Ok so now we have a BeanClass..
now you need to create a bean object whenever the user clicks any item
FoodBean fb = new FoodBean();
fb.setFoodName("get food name from the mapped list here against its number");
now use getFoodName() anywhere in the program, just be careful, the bean object above has local scope if you create it in a method, you need to make a same reference to FoodBean globally and assign the new created object to it, and then use that global reference anywhere in the class.
Further take a look at this simple tutorial

Creating a car class in java

Okay, I need to write code that makes this file
public class HW1tester
{
public static void main(String[] args)
{
Car car1 = new Car();
Car car2 = new Car("Ford", 2013, 20000);
Car car3 = new Car("Audi", 2012, 25000);
Car car4 = new Car();
car2.setPrice(22000);
car2.setYear(2011);
car4.setBrand("Cadillac");
System.out.println("This car is " + car1.getBrand() + ", year " + car1.getYear() + ", price " + car1.getPrice());
System.out.println("This car is " + car2.getBrand() + ", year " + car2.getYear() + ", price " + car2.getPrice());
System.out.println("This car is " + car3.getBrand() + ", year " + car3.getYear() + ", price " + car3.getPrice());
System.out.println("This car is " + car4.getBrand() + ", year " + car4.getYear() + ", price " + car4.getPrice());
System.out.println("The total car number is: " + car1.getNumber());
System.out.println("The total car number is: " + car2.getNumber());
System.out.println("The total car number is: " + car3.getNumber());
System.out.println("The total car number is: " + car4.getNumber());
}
}
So far I have this, but I'm not sure what the hell I'm doing wrong.
public class Car
{
private int yearModel;
private String brand;
private int priceModel;
private int numberModel;
public Car(String b, int year, int price, int number)
{
yearModel = year;
brand = b;
priceModel = price;
numberModel = number;
}
public int getYear()
{
return yearModel;
}
public String getBrand()
{
return brand;
}
public int getPrice()
{
return priceModel;
}
public int getNumber()
{
return numberModel;
}
public void setYear(int year)
{
yearModel = year;
}
public void setBrand(String carBrand)
{
brand = carBrand;
}
public void setPrice(int price)
{
priceModel = price;
public void setNumber(int number)
{
numberModel = number;
}
}
Everytime I run the first code right now it just gives me errors on car1, car2, etc I just can't seem to see what I'm doing wrong at all, I hope somebody can help me out. By the way, I can't make ANY changes to HW1tester.
When creating a new object (car1, car2, etc.), you're not passing in enough variables. Your constructor requires 4 and you're giving, at most, 3 variables when trying to construct a new car object.
You have created parameterized Constructor i.e. public Car(String b, int year, int price, int number)
So when you are trying to create object for the same like, Car car1 = new Car(); then it won't be possible. Because in this you are trying to call default constructor. Which is not present in the class.
While creating object you need to pass 4 arguments.
Moreover, in Car car2 = new Car("Ford", 2013, 20000); You are passing 3 arguments which doesn't match with the constructor.
To create object of class Car, you need to do something like,
Car c = new Car('Volvo', 2014, 25000, 1234);
you need to write overloaded constructors with different parameter sets.
when you call new Car(), java is looking for a ctor with no params, new Car("audi", 2013, 25000) one with 3 params etc.
in your Car.java file:
public Car() {}
then you can set the instance variables with their getters and setters (until you do, their values will be null).
if you want, you can define more, but their signatures have to be different. eg:
public Car(String b, int year) { ... } and public Car(String b, int price) {...} wont work, because they have the same signature.
In class Car, you have a constructor that has 4 parameters. However in the main class, you create a Car with 0 or 3 parameters. In other to run the code, you have to add 2 more constructor, one with 0 parameter, and one with 3 parameters.
public Car() {
}
public Car(String b, int year, int price) {
yearModel = year;
brand = b;
priceModel = price;
}
public Car() {
}
public Car(String b, int year, int price,) {
yearModel = year;
brand = b;
priceModel = price;
}
In that case you have a constructor that has 4 parameters.

Categories

Resources