I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());
Related
I have been tasked with writing a code to create 4 classes(Main, Person,Account,Vehicle)and create objects of the Person class as per user requirements, doing so using an array. I had to store data within the array via user input, and retrieve them as per user choice. Which I believe I have successfully done so. One of the two inputs I had to ask from the user were, "Do you have an Account" and "Do you have a vehicle". If the User answers "Yes", I had to pass the object or something as a reference to the Account and Vehicle class to seclude them separately as well, and when the User asks for the People with an Account and Vehicle, It were to print the details of those specific users only.
.
Here is my code below
Main.java:
package com.company;
import java.util.Scanner;
public class Main {
public static int ids;
static int choice = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menus();
}
public static void conditions(int choice){
switch (choice) {
case 1:
int i;
System.out.println("Enter id of person");
i = sc.nextInt();
Person user2[] = new Person[10];
user2[i] = new Person();
user2[i].setArray(i,user2);
//Getters
int k;
System.out.println("Enter id of existing person to retrieve info or press 0 to go to menu");
int l;
l = sc.nextInt();
if (l == 0) {
menus();
}
else {
System.out.println(user2[l].getName());
System.out.println(user2[l].getGender());
System.out.println(user2[l].getAge());
System.out.println(user2[l].isAccount());
System.out.println(user2[l].isVehicle());
}
case 2:
//Call getters
Account a1=new Account();
a1.getArrays();
case 3:
Vehicle v1=new Vehicle();
v1.printArray();
}
}
public static void menus() {
System.out.println("Choose an option");
System.out.println("1.Enter new person details");
System.out.println("2.Does not work(should display people who want an acc only");
System.out.println("3.Does not work(Should display people who have a vehicle only)");
choice = sc.nextInt();
conditions(choice);
}
}
Person.java:
package com.company;
import java.util.Scanner;
public class Person {
private String name;
private int age;
private String gender;
private static String Account;
private static String Vehicle;
Person array[];
public String isAccount() {
return Account;
}
public void setAccount(String account) {
Account = account;
}
public String isVehicle() {
return Vehicle;
}
public void setVehicle(String vehicle) {
Vehicle = vehicle;
}
public Person[] getArray() {
return array;
}
public void setArray(int i,Person[] array) {
this.array = array;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
name=sc.next();
array[i].setName(name);
System.out.println("Enter age");
age=sc.nextInt();
array[i].setAge(age);
System.out.println("Enter gender");
gender=sc.next();
array[i].setGender(gender);
System.out.println("Enter Yes if you want an account,No if otherwise");
Account=sc.next();
if(Account=="Yes"){
Account user3[] = new Account[10];
user3[i].setArray(i,this.array);
user3[i] = new Account(i,name,gender,Account);
}
else{
array[i].setAccount("No");
}
System.out.println("Enter Yes if you have a vehicle, No if otherwise");
Vehicle=sc.next();
if(Vehicle=="Yes"){
Vehicle user4[] = new Vehicle[10];
user4[i] = new Vehicle();
user4[i].setArray(i,this.array);
}
else{
array[i].setVehicle("No");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Accounts.java:
package com.company;
public class Account extends Person{
Account[] arrays;
private int ages;
private String names;
private String genders;
private String vehicles;
private String accounts;
Account(int id,String names,String genders,String accounts){
arrays[id].setNames(names);
arrays[id].setAges(ages);
arrays[id].setGenders(genders);
arrays[id].setAccounts(accounts);
}
Account(){
}
public com.company.Account[] getArrays() {
return arrays;
}
public void setArrays(com.company.Account[] arrays) {
this.arrays = arrays;
}
public int getAges() {
return ages;
}
public void setAges(int ages) {
this.ages = ages;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getGenders() {
return genders;
}
public void setGenders(String genders) {
this.genders = genders;
}
public String getVehicles() {
return vehicles;
}
public void setVehicles(String vehicle) {
this.vehicles = vehicles;
}
public String getAccounts() {
return accounts;
}
public void setAccounts(String accounts) {
this.accounts = accounts;
}
public void printArray(){
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}
}
My Vehicle class is the same as Accounts.
-To seclude and print
-I have tried to pass the array from the Person class to the Accounts class and Vehicle, If the User does wish to have an Account and has a Vehicle.
-However, upon printing via for loop or a basic getter, I am met with an Error "this.array is null" which probably means my Array isnt being passed or stored within the Account class.
-Maybe there is a simpler way of secluding and printing them, as per the task I have to implement the use of Abstraction, Arrays, Constructors and Functions.
I am new to Java and the Stackoverflow platform, so please forgive me If the formatting of the question isnt precise. Hope to recieve some detailed help on getting around this.
I have a info class Vehicle that has multiple attributes and I have a Moped info class that extends the vehicle class. I need to create a main program that I can add multiple mopeds to an array list and then print them. Here is my attempt:
info class1:
package data;
public class Vehicle {
private float price;
private String color;
private int maximumSpeed;
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color= color;
}
public int getMaximumSpeed() {
return maximumSpeed;
}
public void setMaximumSpeed(int maximumSpeed) {
this.maximumSpeed = maximumSpeed;
}
public String toString() {
return "Price: "+this.price+" Color: "+this.color+" Maximum speed: "+this.maximumSpeed;
}
}
Info class2:
package data;
public class Moped extends Vehicle{
private String Brand;
private String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand= brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString() {
return "Brand: "+this.brand+" Type: "+this.type;
}
}
Main program:
package app;
import java.util.ArrayList;
import java.util.Scanner;
import data.*;
public class ExtendsTest {
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
Moped mp=new Moped();
askForMopedInfo(mp);
lista.add(mp);
printMoped(list);
}
private static void printMoped(ArrayList<Moped> list) {
for (int i=0;i<list.size(); i++) {
System.out.println(list.get(i));
}
}
private static void askForMopedInfo(Moped mp) {
Scanner scanner = new Scanner(System.in);
System.out.print("Brand: ");
String k = scanner.nextLine();
mp.setBrad(k);
System.out.print("Type: ");
k = scanner.nextLine();
mp.setType(k);
System.out.print("Price: ");
int k1 = Integer.parseInt(scanner.nextLine());
mp.setPrice(k1);
System.out.print("Color: ");
k = scanner.nextLine();
mp.setColor(k);
System.out.print("Maximum speed: ");
k1 = Integer.parseInt(scanner.nextLine());
mp.setMaximumSpeed(k1);
}
}
When I run the program I get asked for:
Brand:
Type:
Price:
Color:
Maximum speed:
But the program only prints:
Brand: x Type: x
And I am still not sure how to add multiple mopeds to the array list. Any help would be much appreciated!
Update toString method of your Moped class, like this:
package data;
public class Moped extends Vehicle {
/*
other code
*/
public String toString() {
return super.toString() +" Brand: "+this.brand+" Type: "+this.type;
}
}
to Add more mopeds to the array list, you can do this:
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
While(true){
Moped mp=new Moped();
askForMopedInfo(mp);
list.add(mp);
printMoped(list);
}
}
Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}
I'm working on a task which has the following classes:
Vehicle.java ( Abstract Class)
NewVehicle.java subClass of Vehicle.java
UsedVehicle.java subClass of Vehicle.java
VehicleParser.java used as a parser
Drive Class which is used as main
In the VehicleParser class I determine which object it is. Either it is a NewVehicle object or a UsedVehicle. And in the Drive class I fill an ArrayList with the Vehicle objects.
Now When I'm trying to System.out.println an Arraylist the drive class is just invoking toString method declared in UsedVehicle/NewVehicle but not invoking the method declared in the Vehicle.java class. I need it to first invoke the method toString of Vehicle and then concat the toString of UsedVehicle/NewVehicle with it.
Here is the Code:
Vehicle
public abstract class Vehicle {
protected String make;
protected int modelYear;
protected String motivePower;
protected double licenseFee;
public Vehicle(String make,int modeYear,String motivePower) {
this.make = make;
this.modelYear= modeYear;
this.motivePower = motivePower;
this.licenseFee = 0.0;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public int getModelYear() {
return modelYear;
}
public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}
public String getMotivePower() {
return motivePower;
}
public void setMotivePower(String motivePower) {
this.motivePower = motivePower;
}
public double getLicenseFee() {
return licenseFee;
}
public void setLicenseFee(double licenseFee) {
this.licenseFee = licenseFee;
}
public abstract void computeLicenseFee();
public String toString()
{
return "\nMake:\t\t"+getMake()+
"\nModel Year:\t"+getModelYear()+
"\n Motive Power:\t"+getMotivePower()+
"\nLicense Fee:\t"+getLicenseFee();
}
public static class UsedVehicle extends Vehicle
{
public String previousLicenseState;
public int currentYear;
int yearsOld = 0;
public UsedVehicle(String make, int modelYear, String power, String previousState, int currentYear)
{
super(make,modelYear,power);
this.previousLicenseState = previousState;
this.currentYear = currentYear;
}
public String getPreviousLicenseState() {
return previousLicenseState;
}
public void setPreviousLicenseState(String previousLicenseState) {
this.previousLicenseState = previousLicenseState;
}
public int getCurrentYear() {
return currentYear;
}
public void setCurrentYear(int currentYear) {
this.currentYear = currentYear;
}
public void computeLicenseFee() {
double baseFee = 100.00;
double titleTransferFee = 15.00;
double smogWaiverFee = 0.00;
double smogAbatement = 0.00;
yearsOld = getCurrentYear() - getModelYear();
if(yearsOld > 5)
{
smogWaiverFee = 8.00;
}
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.00;
}
licenseFee = baseFee + smogAbatement + titleTransferFee + smogWaiverFee;
}
public String toString()
{
return "\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
}
public static class NewVehicle extends Vehicle
{
public double vehiclePrice;
public NewVehicle(String make, int modeYear, String motivePower,double price) {
super(make, modeYear, motivePower);
this.vehiclePrice = price;
}
public double getVehiclePrice() {
return vehiclePrice;
}
public void setVehiclePrice(double vehiclePrice) {
this.vehiclePrice = vehiclePrice;
}
public void computeLicenseFee() {
double baseFee = 150.00;
double smogAbatement = 0.00;
double priceFee = 0.00;
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.0;
priceFee = getVehiclePrice()*0.15;
}
licenseFee = baseFee + smogAbatement + priceFee;
}
public String toString()
{
return "Price:\t\t$"+getVehiclePrice();
}
}
}
Parser
public class VehicleParser {
public static Vehicle parseStringToVehicle(String lineToParse)
{
Vehicle vehicleObj = null;
Vehicle.UsedVehicle usedVeh = new Vehicle.UsedVehicle(make, modelYear, power, previousState, currentYear);
return vehicleObj;
}
}
DriveClass
Vehicle obj = VehicleParser.parseStringToVehicle(inputInfo);
vehicleList.add(obj);
System.out.println(vehicleList.get(i));
You are overriding the toString() method. Java doesn't do any special magic here. If you want the super class' method to be called, you need to do so explicitly with the super keyword:
#Override
public String toString()
{
return super.toString() + // Here
"\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
Just consider this example:
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return "C method";
}
}
Basically what's going on here is that when you inherit the parent class, you're overriding everything that's in parent class's method and you're giving new definition to it. By Overriding parent class's method, you're saying that:
I'm giving a new fresh definition to this method. From now onward, for all of my objects and my child's object, this is only going to be the definition that would be considered and any of parent's method definition is void.
Now if you want the parent's method definition to be called before calling this method definition, then you'd have to specifically state that using super.methodName() in your code.
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return super.someMethod() + "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return super.someMethod() + "C method";
}
}
When you call the subclass methods the overridden methods will be called and all the definitions in the parent's method will be overridden and you will get only the overridden method definition. So inprder to use the parents' method definition as well you need to use the super() method in your child class method...
return super.toString() + " is a new car!";
I'm just trying to Override and use the toString method to print some information about my classes.
Can someone please provide advice as to how I would do this?
I've never done this before, and I'm becoming stuck.
My Base Class:
public class Vehicle {
int seatNumber;
int numberMade;
int yearMade;
public Vehicle(int seatNumber, int numberMade, int yearMade) {
this.seatNumber = seatNumber;
this.numberMade = numberMade;
this.yearMade = yearMade;
}
public int getSeatNumber() {
return seatNumber;
}
public int getNumberMade() {
return numberMade;
}
public int getYearMade() {
return yearMade;
}
}
A derived class:
public class Car extends Vehicle {
public int topSpeed;
public Car(int seatNumber, int numberMade, int yearMade, int topSpeed) {
this.seatNumber = seatNumber; //takes the value you pass as parameter
this.numberMade = numberMade; // and stores it into the instance variable
this.yearMade= yearMade;
this.topSpeed = topSpeed;
}
}
Main Class:
public class Assignment2 {
public static void main(String[] args) {
Car myCar = new Car(5, 20000, 1998, 180);
Motorbike myMotorbike = new Motorbike(1, 5000, 2015, 300);
System.out.println(myCar);
System.out.println(myMotorbike);
}
}
You can do it like this:
public class Vehicle {
int seatNumber;
int numberMade;
int yearMade;
// Getters, setters, constructor, etc
#Override
public String toString() {
return String.format("[Vehicle] seats: %d, number made: %d, yearMade %d", seatNumber, numberMade, yearMade);
}
}
Same for the other Class
I'm just trying to Override and use the toString method to print some information about my classes
There are 2 ways you can override a method in the subclass.
Override by modification
Override it with new implementation
Can someone please provide advice as to how I would do this?
Overridding in Java is very simple. Just rewrite the method with similar method signature in the subclass according to the method in its super class.
Below shows an example of overriding by modification:
class Animal
{
#Override
public String toString(){
return "An animal";
}
}
class CatFamily extends Animal{
#Override
public String toString(){
return super.toString() + " from the cat family.";
}
}
class Lion extends CatFamily{
#Override
public String toString(){
return super.toString() + " - A Lion";
}
}
Create a super & subclass instance for testing:
public static void main(String[] args)
{
System.out.println(new Animal());
System.out.println(new CatFamily());
System.out.println(new Lion());
}
OUTPUT:
An animal
An animal from the cat family.
An animal from the cat family. - A Lion