Car Program using Getters and Setters Issues - java

For this Program the instance variables make and model need to be a string, price needs to be a double which I already have, but not sure what to do with year that needs to be of type int and greater then 1900. I then need to make a constructor with argument which I have done as well but the toString needs to return the string representation of a Car object with the setters and getters methods. So I am having an issue trying to come up with something for the setters and if I am doing this section right.
public class Car {
private String make;
private String model;
private double price;
private int year;
public Car(String make, String model, double price, int year) {
this.make = make;
this.model = model;
this.price = price;
this.year = year;
}
private String getMake() {
return make;
}
private void setMake(String make) {
this.make = make;
}
private String getModel() {
return model;
}
private void setModel(String model) {
this.model = model;
}
private double getPrice() {
return price;
}
private void setPrice(double price) {
this.price = price;
}
private int getYear() {
return year;
}
private void setYear(int year) {
this.year = year;
}
public String toString() {
return "Make of Car: " + getMake() + "\n Model of Car: " + getModel()
+ "\n Price of Car: " + getPrice() + "\n Year of Car: " + getYear();
}
}
This section is the CarTest driver and I am not sure if I did this properly. I have to have a Main method that Instantiates a Car object car1 by invoking the argument constructor and display to the console the string representation of the object car1 using the method toString. Also asking the user to enter values for each instance variable and use the setter type methods to assign the entered values to the corresponding instance variables of the object car1 then I need to display the string representation of the object car1 by invoking the toString method. Am I doing this part right?
public class CarTest {
static Car car1;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Make?");
String make = scan.nextLine();
System.out.print("Model?");
String model = scan.nextLine();
System.out.print("Price?");
double price = scan.nextDouble();
System.out.print("Year?");
int year = scan.nextInt();
car1 = new Car(make,model,price,year);
System.out.print(car1.toString());
}
}

You can either do the checking when taking the user input, or the constructor (or both)
int year = 0;
while (year < 1900) {
System.out.println("Year? ");
year = scanner.nextInt();
}

Everything looks good to me. Maybe you don't need to have the getters if you have the toString method, which returns all the attributes of the car. Juste have the variables and the to string in the return and remove the getters
Good work!

Related

I have my constructor class written, but I need to test it. How do I do that?

I'm a relatively new Java programmer, and I'm working on learning Constructors. I've gotten the format of how to make the Constructor itself down, but my Computer Science teacher requires me to write some more lines of code that will make sure my Constructor works.
I've looked on other sites, and it doesn't really give me what I need.
I've tried using what I thought might logically work (typing "a.variable()" as an object, but that didn't work either.
class Car {
public String make;
public String model;
public int numberOfDoors;
public int topSpeed;
public int price;
Car(String make, String model, int numberOfDoors, int topSpeed, int price){
this.make = make;
this.model = model;
this.numberOfDoors = numberOfDoors;
this.topSpeed = topSpeed;
this.price = price;
}
Car(String make, String model, int topSpeed, int price){
this.make = make;
this.model = model;
this.numberOfDoors = 4;
this.topSpeed = topSpeed;
this.price = price;
}
Car(int numberOfDoors, int topSpeed, int price){
this.make = "unknown";
this.model = "unknown";
this.numberOfDoors = numberOfDoors;
this.topSpeed = topSpeed;
this.price = price;
}
Car(String make, String model, int numberOfDoors){
this.make = make;
this.model = model;
this.numberOfDoors = numberOfDoors;
this.topSpeed = 90;
this.price = 0;
}
}
I'm looking for something that will print out something like:
1990 Mustang, 4 doors, 140 mph, $40000
All you need to do is to create an instance of the class Car using an appropriate constructor.
public class Example {
public static void main(String[] args) {
Car car = new Car("Mustang", "1990", 4, 140, 40000);
}
}
With the instance car created, you can access its fields.
For example,
int numberOfDoors = car.numberOfDoors;
We usually make fields private and access them via getters:
int numberOfDoors = car.getNumberOfDoors();
It will work assuming there is a method getNumberOfDoors defined as
public int getNumberOfDoors() {
return this.numberOfDoors;
}
//You Car class should look like this
public class Car {
public String model;
public int numberOfDoors;
public int topSpeed;
public int price;
// This is the Car class constructor
public Car(String model, int numberOfDoors, int topSpeed, int price) {
this.model = model;
this.numberOfDoors = numberOfDoors;
this.topSpeed = topSpeed;
this.price = price;
}
}
// This is where you call the Car class. You create a new class MyCar to call my class
public class MyCar {
public static void main(String[] args) {
Car car = new Car("1990 Mustang", 4, 140, 40000);
System.out.println(car);
// Output : 1990 Mustang, 4, 140, 40000
}
}

Simplify java program using inheritance

I'm currently learning inheritance in java. I have a superclass called Students with subclasses UndergradStudents & GraduateStudents. Both of them have a method called deansHonourList. In the undergrad deansHonourList method it checks if the GPA is greater than 3.5 to qualify for the deans list and for the graduate subclass the gpa has to be greater than 3.75, I have to remove the methods in the subclasses and create one method in the superclass that determines if the student qualifies for the deans honour list. Here is my code so far.
import java.io.*;
public class Activity6C {
public static void main(String[] args) {
Student[] students = new Student[4];
students[0] = new UndergradStudent(8032, "Casper", 2.78, 2);
students[1] = new GraduateStudent(3044, "Sheena", 3.92, "Natural Language Processing");
students[2] = new UndergradStudent(6170, "Yolanda", 4.26, 3);
students[3] = new GraduateStudent(1755, "Geordi", 3.58, "Human-Computer Interaction");
printStudents(students);
printDeansList(students);
System.out.println("\nEnd of processing.");
}
public static void printStudents(Student[] students) {
System.out.println("\nList of all students:\n");
for (int i = 0; i < students.length; i++) {
System.out.println(i + 1 + ": " + students[i]);
}
}
public static void printDeansList(Student[] students) {
System.out.println("\nDean's honour list:\n");
for (int i = 0; i < students.length; i++) {
if (students[i].deansHonourList()) {
System.out.println(students[i]);
}
}
}
}
class Student {
private int number;
private String name;
private double gpa;
public Student(int number, String name, double gpa) {
this.number = number;
this.name = name;
this.gpa = gpa;
}
public double getGPA() {
return gpa;
}
public boolean deansHonourList() {
//Here is where i make my code to determine honour list students
return false;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa);
this.year = year;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= 3.5)
result = true;
return result;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
}
class GraduateStudent extends Student {
private String thesis;
public GraduateStudent(int number, String name, double gpa, String thesis) {
super(number, name, gpa);
this.thesis = thesis;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= 3.75)
result = true;
return result;
}
public String toString() {
return "Graduate: " + super.toString() + " thesis: " + thesis;
}
}
Note: This is an exercise and it's not worth much but I would like a hint in the right direction. Here is what the question also specifies.
I have to make it work without using instanceof or getClass(), and without adding any more if-else statements or instance variables. There should be no deansHonourList() method in either GraduateStudent or UndergraduateStudent, and the getGPA() method can be removed.
The hint i got was to add another instance method to the superclass and override it in the subclasses as necessary; call that method in your deansHonourList() method.
I can't think of a way to do this. I mean what can I put in the new instance method that I would make, and then override it in the subclasses.
Thank you for reading my question or any hints you are able to give me.
You'll need a (possibly abstract) method which returns the minimum GPA score acceptable to be considered for the honours list, maybe something like
abstract class Student {
private int number;
private String name;
private double gpa;
public Student(int number, String name, double gpa) {
this.number = number;
this.name = name;
this.gpa = gpa;
}
public double getGPA() {
return gpa;
}
public abstract double getMinimumHonourListGPA();
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= getMinimumHonourListGPA()) {
result = true;
}
return result;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
Then you could implement doing something like...
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa);
this.year = year;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
#Override
public double getMinimumHonourListGPA() {
return 3.5;
}
}
Now, if that's not acceptable, you will need to pass the minimum GPA score via the constructor to the parent class, something like...
class Student {
private int number;
private String name;
private double gpa;
private double minimumHonourListGPA;
public Student(int number, String name, double gpa, double minimumHonourListGPA) {
this.number = number;
this.name = name;
this.gpa = gpa;
this.minimumHonourListGPA;
}
public double getGPA() {
return gpa;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= minimumHonourListGPA) {
result = true;
}
return result;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa, 3.5);
this.year = year;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
}
for example
Ok, what if you had a method 'requiredGPA()', which returned the GPA required to get on the Deans Honour List?
You would then override this method in the subclasses to return their different requirements, and the superclass's deansHonourList() would use the value returned from this method to decide if the student was on the list?
I could give a code example if needed... let me know if I haven't been clear in this answer?
Edit- looks like MadProgrammer has hit the idea I was going for here.
This is an example of Facade design pattern.
Check here.
This pattern is about providing a simple interface to hide the underlying complexity. Interface is used for the invocation of a single and during the run time JVM will determine which method to call. This method is determined by the implementing class of the object on which method was invoked.
In your case Student is going to work as the interface. As others suggested you can use an abstract class with abstract method deansHonourList or you can use an empty implementation.
Now suppose we have empty constructors in all three classes.
Student student1 = new Student();
Student student2 = new UnderGraduateStudent();
Student student3 = new GraduateStudent();
Since a parent class reference variable can hold instance of the child class we are able to assign objects of UnderGraduateStudent and GraduateStudent to the Student type reference variables.
All these three classes have method deansHonourList.
When we call this method on all the three objects as following
student1.deansHonourList(arguments...)
student2.deansHonourList(arguments...)
student3.deansHonourList(arguments...)
JVM will find the correct class from which it has to invoke the method by checking the type of the student1, student2, student3 instances.
Only one of these methods will be called (unlike constructor where super class constructor is called in subclass constructor).
Even if the deansHonourList is called on parent class reference, the method from the child class is called as the reference holds child class instance.
This is called Method Overriding.
Check this out.
Overriding only works in case of non static methods, in case of static methods, parent class methods are called. Since static members are part of the class not the class instance, instance plays no role in the method resolution.
This is called Method Hiding

Create a method with unknown number and type of arguments in java

I'm working with primefaces datatables, and at the same time I'm using Triple datastores (Jena TDB) instead of traditional databases. I'm going to create an object like primefaces showcase sample below;
public class Car {
private String model;
private int year;
private String manufacturer;
private String color;
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
here everything is clear and car object has definite arguments like model, year, ... however in my program based on user selection from the menu bar, I have to call quite different objects with various properties as arguments and do the same as shown in the showcase. I'm quite new in java and I really confused how can I solve this problem.
As an example my program object could be a company with (Name, Address, Email, Tel ,... ) arguments, or it could be a Machine with quite different properties like (Name, Model, production date, Specs. and etc).
Thanks in advance for your responses.
Not exactly understood the explanation you have provided. I can give you one answer against your title: Create a method with unknown number and type of arguments in java
You can use Java args along with Object class.
package com.misc;
public class NNumberOfObj {
public static void acceptNNumberOfAnyTypeofObjects(Object... args) {
System.out.println("Total objects are: " + args.length);
//Your further implementation goes here.
}
public static void main(String[] args) {
String s = new String("Nikhil");
Integer i = 10;
Employee emp = new Employee(10, "Kunal");
acceptNNumberOfAnyTypeofObjects(s, i, emp);
}
}
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
}

Why are my codes error today and fine yesterday?

import java.util.Scanner;
public class CarTest {
/**
* #param args
*/
public static void main(String[] args) {
//create a Scanner object
Scanner input = new Scanner(System.in);
/**
*Creates a car! object from the Car class
*with the passing of these arguments
*year, make, model, price
*/
Car car1 = new Car("2008", "Nissan", "Pathfinder", "10,000");
//display toString using car1 object
System.out.println(car1.toString());
//user input for year
System.out.println("Please list your automobile for sale: " +
"\nPlease enter the year? ");
//String newYear variable is created for CarTest class
String newYear = input.nexLine();
//set year in car class for Car1 object to String newYear
car1.setYear(newYear);
//user input for make
System.out.println("Please enter the make? ");
//String newMake variable is created for CarTest class
String newMake = input.nextLine();
//set make in car class for Car1 object to String newMake
car1.setMake(newMake);
//user input for model
System.out.println("Please Enter the model?");
//String newModel variable is created for CarTest class
String newModel = input.nextLine();
//set model in car class for Car1 object to String newModel
car1.setModel(newModel);
//user input for price
System.out.println("How much would you sell your car for?");
//String newPrice variable is created for CarTest class
String newPrice = input.nextLine();
//set price in car class for Car1 object to String newPrice
car1.setPrice(newPrice);
//displays the new info to the screen
System.out.println(car1.toString());
}
}
from
public class Car {
//class variables are created
private String year;
private String make;
private String model;
private String price;
//default constructor
public Car() {
}
//constructor with arguments
public Car(String year, String make, String model, String price) {
this.year = year;
this.model = model;
this.make = make;
this.price = price;
}
//get make of the vehicle
public String getMake() {
return make;
}
//set make for vehicle
public void setMake(String make) {
this.make = make;
}
//get model of the vehicle
public String getModel(){
return model;
}
//set model for vehicle
public void setModel(String model) {
this.model = model;
}
//get price of the vehicle
public String getPrice() {
return price;
}
//set price for vehicle
public void setPrice(String price) {
this.price = price;
}
//get year of the vehicle
public String getYear() {
return year;
}
//set year for vehicle
public void setYear(String year) {
this.year = year;
}
public String toString() {
return "For Sale By Owner: " + year + " " + make + " " + model +
"\nSelling Price: $" + price + "\n ";
}
}
It worked fine when i handed it last week for an assignment, but today, when i came to my computer for a new homework, I found red x's on my car.java, and carTest.java.
My eclipse is saying that : from carTest.java is full of errors and:
error: main method not found in class homework.cartest. please define the main method
public static void main(String[] args)
error is in the way I defined CAR1:
Car car1 = new Car("2008", "Nissan", "Pathfinder", "10,000");
and the ways i am getting the inputs
String newYear = input.nexLine();
String newMake = input.nextLine();
String newModel = input.nextLine();
String newPrice = input.nextLine();
with the input.nextLine(); being underlined as an error in the code in eclipse.
also in the Car.java. the method String toSTring() causes an error stating "change toString() type to String type.
it worked fine when I handed it and got a good grade for it, but today I noticed my codes to be errors, when all was okay yesterday?
Is the file listed under package/project Homework?
If not, reading your error-message correctly, you're trying to run something that doesn't exist.
At the same time, as said above, you could be experiencing filepath issues. Creating a new project and copy-pasting your code (refactored copy) is usually the quickest solution.
Clean and build the project. May be an anomaly with your Java build path
Copied your project and runned it. Only thing that is wrong with it is:
String newYear = input.nexLine();
should be:
String newYear = input.nextLine();
For the rest, it works fine.
And in the toString method you should add an #override annotation
#Override
public String toString() {
return "For Sale By Owner: " + year + " " + make + " " + model
+ "\nSelling Price: $" + price + "\n ";
}
Also make sure your project is called CarTest and Source packages package cartest

How can I access the value of a private attribute in an abstract class in a subclass object?

I am taking a class in Java and this question relates to one of the exercises I am to complete. I am trying to print out the contents of an array of objects created from 2 subclasses of an abstract superclass. I am able to create the objects and store them in an array, but when I print out the contents of the array I'm only able to get the last instance of the "age" and "weight" attributes of the superclass. As you can see they are private attributes. Is there a way to access the value of those attributes when the object is created? I've done a fair bit of reading and I'm confused as to whether I can do it and if I can, then how?
My code:
public abstract class Parent {
private static int age;
private static double weight;
public Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public static int getAge() {
return age;
}
public static double getWeight() {
return weight;
}
}
public class Child1 extends Parent {
private String name, owner, petInfo;
protected int age;
protected double weight;
public Child1(int age, double weight, String name, String owner) {
super(age, weight);
this.name = name;
this.owner = owner;
}
public String toString() {
petInfo = "Pet's name: " + this.getName() + "\nPet's age: " + getAge() + " years\nPet's weight: " + getWeight() + " kilos\nOwner's name: " + this.getOwner();
return petInfo;
}
}
public class Child2 extends Parent {
public String wildInfo;
public Child2(int age, double weight) {
super(age, weight);
}
public String toString() {
wildInfo = "The wild animal's age: " + getAge() + "\nThe wild animal's weight: " + getWeight();
return wildInfo;
}
}
public class Console {
public static void main(String[] args) {
Parent ref[] = new Parent[5];
for(i = 0; i < 5; i++) {
//user input here
Child1 pet = new Child1(age, weight, name, owner);
ref[i] = pet;
//more user input
Child2 wild = new Child2(age, weight);
ref[i] = wild;
}
//print contents of array
for(Parent item : ref)
System.out.println("\n" +item.toString()+ "\n");
My understanding is that I can only access the attributes of the superclass through the methods. When I use the getAge() and getWeight() methods in the toString() I am not getting the values entered for each object, only the last value the attributes had.
Any help would be greatly appreciated. Cheers.
Don't use static variables for age and weight:
private static int age;
private static double weight;
The values of static variables are the same for all objects of this type since these variables are be class variables, not instance variables. These guys should be instance or non-static fields which will make them unique for each instance of this class (or instances of child classes).
Then in your Child class, get rid of these shadowing variables, since they will shadow the similarly named field in the Parent class:
public class Child1 extends Parent {
private String name, owner, petInfo;
protected int age; // ***** get rid of, since it shadows
protected double weight; // ***** get rid of, since it shadows
Instead, wherever you use these, use the getters and setters in the Child class.
There were errors in the above program.
Corrected the static methods in Parent Class into non-static methods.
Sample Code:
import java.util.Scanner;
abstract class Parent {
private int age;
private double weight;
public Parent(int age, double weight) {
this.age = age;
this.weight = weight;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
}
class Child1 extends Parent {
private String name, owner, petInfo;
public Child1(int age, double weight, String name, String owner) {
super(age, weight);
this.name = name;
this.owner = owner;
}
public String toString() {
petInfo = "Pet's name: " + this.getName() + "\nPet's age: " + getAge() + " years\nPet's weight: " + getWeight() + " kilos\nOwner's name: " + this.getOwner();
return petInfo;
}
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
}
class Child2 extends Parent {
public String wildInfo;
public Child2(int age, double weight) {
super(age, weight);
}
public String toString() {
wildInfo = "The wild animal's age: " + getAge() + "\nThe wild animal's weight: " + getWeight();
return wildInfo;
}
}
public class Console {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Parent ref[] = new Parent[2];
//int weight=10;
//int age=5;
//String name="parrot";
//String owner="rajesh";
for(int i = 0; i < 2; i++) {
System.out.println("Enter the name");
String name=in.next();
System.out.println("Enter the age ");
int age=in.nextInt();
System.out.println("Enter the weight");
double weight=in.nextDouble();
System.out.println("Enter the owner");
String owner=in.next();
//user input here
Child1 pet = new Child1(age, weight, name, owner);
ref[i] = pet;
//more user input
if (i==1)
{
break;
}
System.out.println("Enter the name");
name=in.next();
System.out.println("Enter the age ");
age=in.nextInt();
System.out.println("Enter the weight");
weight=in.nextDouble();
System.out.println("Enter the owener");
owner=in.next();
Child2 wild = new Child2(age, weight);
ref[++i] = wild;
}
//print contents of array
for(Parent item : ref)
System.out.println("\n" +item.toString()+ "\n");
}
}

Categories