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.
Related
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.
I have a homework assignment to Create an app that allows users to enter information about a collection of board games. The data entered by the user will be stored/accessed through a class. The steps I am given are to create the class, named BoardGame, for storing a collection of (analog or non-digital) board games with 8 fields. I then make a constructor that stores ONLY the first three fields. Then, for all fields, I create individual get and set methods, along with a toString method to print all the data for all the fields. Then within the main method there are 3 parts. Part 1, create an array called boardGames that has an array size of 4 (Right now I just have it set to 1 for testing). Create a loop to ONLY get the first three pieces of information. Part 2. AFTER the three basic pieces of the board game have been entered by the user, create a second loop to get the remaining five information from the user. Part 3. Once all the remaining data has been entered and stored by the user, create a third loop to print all the data in the array using the toString method (from the BoardGame class) for each object.
I think everything in BoardGame is set up correctly. I can also get Either step 1 or step 2 working with step 3. the issue is that I can't get step 1 AND step 2 to work at the same time. the Array either has the first 3 pieces of info or the last 5 pieces
I have tried making multiple constructors. I have tried a bunch of stuff that are probably all rookie errors XD
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
BoardGame[] boardGame = new BoardGame[1];
// Loop for first three peices of info
for (int i = 0; i < boardGame.length; i++) {
String gameName, publisherName, yearPublished;
System.out.print("What is the name of the board game? ");
gameName = scnr.nextLine();
System.out.print("Publisher name? ");
publisherName = scnr.nextLine();
System.out.print("Year published? ");
yearPublished = scnr.nextLine();
boardGame[i] = new BoardGame (gameName, publisherName, yearPublished);
}
// Loop for remaining peices of info
for (int i = 0; i < boardGame.length; i++) {
String genre;
double price;
int minPlayerNum, maxPlayerNum, playTime;
System.out.print("How much does " + boardGame[i].getGameName() + " cost? ");
price = scnr.nextDouble();
System.out.print("What is the minimum number of players for " + boardGame[i].getGameName() + "? ");
minPlayerNum = scnr.nextInt();
System.out.print("What is the maximum number of players for " + boardGame[i].getGameName() + "? ");
maxPlayerNum = scnr.nextInt();
System.out.print("What is the game genre? ");
scnr.nextLine();
genre = scnr.nextLine();
System.out.print("How long on average does it take to play " + boardGame[i].getGameName() + " (in minutes)? ");
playTime = scnr.nextInt();
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
}
for (int i = 0; i < boardGame.length; i++) {
System.out.println(boardGame[i].toString());
System.out.println();
}
}
}
public class BoardGame {
// Fields
private String gameName;
private String publisherName;
private String yearPublished;
private double price;
private int minPlayerNum;
private int maxPlayerNum;
private String genre;
private int playTime;
// Constructor 1
public BoardGame(String gameName, String publisherName, String yearPublished) {
this.gameName = gameName;
this.publisherName = publisherName;
this.yearPublished = yearPublished;
}
// Constructor 2
public BoardGame(double price, int minPlayerNum, int maxPlayerNum, String genre, int playTime) {
this.price = price;
this.minPlayerNum = minPlayerNum;
this.maxPlayerNum = maxPlayerNum;
this.genre = genre;
this.playTime = playTime;
}
// Get Methods
public String getGameName() {
return gameName;
}
public String getPublisherName() {
return publisherName;
}
public String getYearPublished() {
return yearPublished;
}
public double getPrice() {
return price;
}
public int getMinPlayerNum() {
return minPlayerNum;
}
public int getMaxPlayerNum() {
return maxPlayerNum;
}
public String getGenre() {
return genre;
}
public int getPlayTime() {
return playTime;
}
// Set Methods
public void setGameName(String gameName) {
this.gameName = gameName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public void setYearPublished(String yearPublished) {
this.yearPublished = yearPublished;
}
public void setPrice(double price) {
this.price = price;
}
public void setMinPlayerNum(int minPlayerNum) {
this.minPlayerNum = minPlayerNum;
}
public void setMaxPlayerNum(int maxPlayerNum) {
this.maxPlayerNum = maxPlayerNum;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setPlayTime(int playTime) {
this.playTime = playTime;
}
// Prints the data FIX_ME if min and max number of players is the same, only print one number
public String toString() {
return "Game name: " + gameName + "\nPublisher Name: " + publisherName +
"\nYear Published: " + yearPublished + "\nPrice: " + price +
"\nMinimum number of players: " + minPlayerNum + "\nMaximum number of players: "
+ maxPlayerNum + "\ngenre: " + genre + "\nPlay time: " + playTime;
}
}
`
Depending on how I have it set up, either the first three won't have an assigned value, or the last 5 won't. It is currently set up in a way that makes the first three data pieces null.
In your second loop, instead of overriding the current BoardGame object by a new one like in your current code:
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
You should retrieve the BoardGame already stored in your array by the first loop, and call your setters on it:
boardGame[i].setPrice(price);
boardGame[i].setMinPLayerNum(minPlayerNum);
//etc...
Like so, you won't be overriding/replacing any values, you are just adding properties to the already created object.
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!
Abstract Class Java Why is my program only printing 0.00?
public class TestEmployee
{
public static void main(String[] args)
{
Employee[] folks = new Employee[4];
folks[0] = new SalariedEmployee("Suzy",123,520000.00);
folks[1] = new WageEmployee("Fred",456,7.50,40);
folks[2] = new SalariedEmployee("Harry",234,45000.00);
folks[3] = new WageEmployee("Rita",345,7.76,38);
for(int i=0; i<folks.length; i++)
{
System.out.println(folks[i].getName()
+ " earns " + folks[i].getMonthlyPay() + " each month");
}
}
}
I added the missing classes needed to make
the program compile and run properly
abstract class Employee
{
private String name;
private int number;
public abstract double getMonthlyPay();
public Employee(String name, int number, double salary)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public Employee(String name, int number, double salary, int hours)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public String getName()
{
return this.name;
}
public int getNumber()
{
return this.number;
}
public String setName(String name)
{
this.name = name;
return this.name;
}
public int setNumber(int number)
{
this.number = number;
return this.number;
}
}
Please provide an explanation or insight as to why my program is only printing zeroes. I think this is where my problem lies
class SalariedEmployee extends Employee
{
private double yearSalary;
public SalariedEmployee(String name, int number, double salary)
{
super(name, number, salary);
yearSalary = getMonthlyPay();
}
public double getMonthlyPay()
{
double monthlyPay = yearSalary / 12;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
class WageEmployee extends Employee
{
private double wage;
private int hours;
public WageEmployee(String name, int number, double salary, int hours)
{
super(name, number, salary, hours);
}
public double getMonthlyPay()
{
double monthlyPay = wage * hours * 4;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
It’s not too difficult to track back to where the 0.00 comes from.
In you for loop in main you use folks[i].getMonthlyPay() to get the number to print. So let’s look into the implementations of getMonthlyPay(). There are two implementations, one in SalariedEmployee and one in WageEmployee.
In case of a SalariedEmployee the getMonthlyPay method uses the value of the field yearSalary. Which value is assigned to yearSalary? Have you editor or IDE find all the occurrences of yearSalary to see where a value is assigned to it. You will see that it happens nowhere. Since yearSalary is a field (more precisely, an instance variable), Java assigns 0.00 to it from the start (local varaibles inside a method are different). Since you never assign any other value, the value is still 0.00 when getMonthlyPay() divides it by 12 and returns the result. So this is where 0.00 comes from. Can you find a way to fix it?
In case of a WageEmployee — you should try the same exercise yourself, find out where the value comes from in WageEmployee.getMonthlyPay(). This time you will need to find out both where the value of wage and where the value of hours come from. Happy searching.
I'm getting this error message for my getYear, getMake, and getModel methods within my class car, because apparently they aren't being passed arguments. It appears to me that they are being passed arguments, but I'm still in a beginner in Java, so I'm not sure where I messed up.
public class NextCar {
public static final void main(String args[]) {
//Creates objects from Car class
Car c = new Car ();
Car c1 = new Car ();
Car c2 = new Car ();
Car c3 = new Car ();
//First object
//Prints mileage
c.start();
c.moveForward(6);
c.moveBackward(2);
c.moveForward(4);
System.out.println ("The car went " + c.mileage() + " miles.");
//Second object
//Prints year of car
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
//Third object
//Prints year and make of car
c2.getYear(2055);
c2.getMake("Google");
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
//Fourth object
//Prints year, make, and model of car
c3.getYear(2060);
c3.getMake("Google");
c3.getModel("Smart");
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
c3.getMake() + " and the model is " + c3.getModel());
}
}
//creates Car class
class Car {
public int year = 0;
public String make = "";
public String model = "";
public int miles = 0;
public boolean power = false;
public void start() {
power = true;
}
public void moveForward(int mf) {
if (power == true) {
miles += mf;
}
}
public void moveBackward(int mb) {
if (power == true) {
miles -= mb;
}
}
public int mileage() {
return miles;
}
public int getYear(int y) {
year = y;
return year;
}
public String getMake(String ma) {
make = ma;
return make;
}
public String getModel(String mo) {
model = mo;
return mo;
}
}
Your Car class getYear method takes an integer input:
public int getYear(int y)
but you call it few times without providing an input
System.out.println("The year of the car is " + c1.getYear());
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
thats the reason for your errors.
You probably want two methods getYear(to get the year value) and setYear (to set the year value) but you have defined only one. Probably this is what you need:
public void setYear(int y) {
year = y;
}
public int getYear() {
return year;
}
Furthermore look here:
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
the getYear return a value. so you could do
int year = c1.getYear(2050);
System.out.println("The year of the car is " + year);
Similar for the others. Or as Juned said, use appropiate getters/setters