I have two classes I have posted here (plus a computer class that the objects are being created from).
When I try to use my findSys method, my method returns "null" no matter what. I am trying to compare the "search" variable the user inputs as a findSys parameter against null, and if it's null, it should output the message I have underneath the "else" clause. But instead, its just returning null no matter what. Stuck here.
import java.util.Scanner;
public class SystemTester {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String search;
ComputerStore cpu1 = new ComputerStore();
cpu1.add("Pentium II", 32, "2080", "Asus 370", "Corsair", 5, 123, 5);
cpu1.add("Pentium I", 16, "Nvidia 1080", "Asus 270", "CoolerMaster1", 5, 123, 5);
cpu1.add("Pentium III", 4, "GTX 1060", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("AMD", 4, "GTX 980", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("AMD Ryzen", 4, "GTX 680", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("Core I5", 4, "GTX 1080ti", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("Core I7", 4, "GTX 1060 SLI", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("Core I9", 4, "GTX 780", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("AMD Ryzen 2", 4, "Voodoo2", "Gigabyte", "Corssair 2", 5, 123, 5);
cpu1.add("I7 5820k", 4, "Voodoo1", "Gigabyte", "Corssair 2", 5, 123, 5);
ComputerStore cpu2 = new ComputerStore();
cpu2.add("Haswell", 64, "Nvidia 1080", "Aztek", "Corsair", 3.5, 455, 5.5);
System.out.println("Please enter a CPU to search for (Press q to quit)");
search = scan.nextLine();
while (!"q".equals(search)) {
if (search != null) {
System.out.println(cpu1.findSys(search));
}
else {
if (search.equals(null))
System.out.println("test");
}
System.out.println("Please enter a CPU to search for (Press q to quit)");
search = scan.nextLine();
}
}
}
public class ComputerStore {
private Computer[] systems;
private int sysNumbers;
public ComputerStore() {
systems = new Computer[200];
sysNumbers = 0;
}
public void add(String c, int r, String g, String m, String p, double co, int sn, double d) {
systems[sysNumbers++] = new Computer(c, r, g, m, p, co, sn, d);
}
public String toString() {
String result = "";
for (int i = 0; i < sysNumbers; i++)
result += systems[i].toString() + "\n";
return result;
}
public String findSys(String c) {
for (int i = 0; i < sysNumbers; i++) {
if (systems[i] != null && systems[i].getCpu().equals(c))
return systems[i].getMotherboard();
}
return null;
}
}
//
//This program will create Computer objects with different data members
//and will also upgrade those data members based on setters. This program
//also has a depreciation function and upgrade function. This (Computer) is the class
//and the SystemBuilder class is the class used for creating the objects.
public class Computer {
// Data Members - These belong to the class and are private.
// They all go to new objects.
private String cpu;
private int ram;
private String gpu;
private String motherboard;
private String psu;
private double cost;
private int serialnumber;
private double depreciation;
// Initial constructor with no arguments
Computer() {
cpu = "";
ram = 0;
gpu = "";
motherboard = "";
psu = "";
cost = 0.0;
serialnumber = 0;
depreciation = 0.0;
}
// Constructor with data members
Computer(String c, int r, String g, String m, String p, double co, int sn, double d) {
cpu = new String(c);
ram = r;
gpu = new String(g);
motherboard = new String(m);
psu = new String(p);
cost = co;
serialnumber = sn;
depreciation = d;
}
// Getters, allow retrieval of data members from outside of class
public String getCpu() {
return cpu;
}
public int getRam() {
return ram;
}
public String getGpu() {
return gpu;
}
public String getMotherboard() {
return motherboard;
}
public String getPsu() {
return psu;
}
public double getCost() {
return cost;
}
public int getSerialnumber() {
return serialnumber;
}
public double getDepreciation() {
return depreciation;
}
// Setters, allow setting of data members from outside of class
public void setCpu(String c) {
cpu = new String(c);
}
public void setRam(int r) {
ram = r;
}
public void setGpu(String g) {
gpu = new String(g);
}
public void setMotherboard(String m) {
motherboard = new String(m);
}
public void setPsu(String p) {
psu = new String(p);
}
public void setCost(double co) {
cost = co;
}
public void setSerialnumber(int sn) {
serialnumber = sn;
}
public void setDepreciation(double d) {
depreciation = d;
}
// Boolean below will compare computers to see if equal
// based on same motherboard SN#.
public boolean equals(Computer c) {
if (this.serialnumber == (c.serialnumber)) {
return true;
} else {
return false;
}
}
// To string method will print characteristics about object.
public String toString() {
return ("CPU:\t\t" + cpu + "\n" + "RAM:\t\t" + ram + "\n" + "GPU:\t\t" + gpu + "\n" + "Motherboard:\t"
+ motherboard + "\n" + "PSU:\t\t" + psu + "\n" + "Cost:\t\t" + "$" + cost + "\n" + "SN#:\t\t"
+ serialnumber + "\n" + "Depreciation:\t" + "$" + depreciation + " (annually)");
}
// A method to depreciate the cost of the computer
// The formula is observed below, but this is a
// straight line depreciation equation, calculated based
// on the values the user passes into the function. This method
// will show an output of annual depreciation based on useful
// life, entered in "years" by the user.
public void depreciate(double purchasePrice, double salvageValue, double lifeSpanYears) {
double depreciableCost;
double annualDepreciation;
depreciableCost = purchasePrice - salvageValue;
annualDepreciation = depreciableCost / lifeSpanYears;
depreciation = annualDepreciation;
}
// A method to upgrade the ram or the video card
// The method will accpet argumetns for ram (in int) and a gpu (string).
public void upgrade(int newRam, String newGpu) {
ram = newRam;
gpu = new String(newGpu);
}
}
For me your implementation is perfectly working. Here I attached screenshot, may be you did something wrong during console input when you are taking input search text.Console out put snapshot
Ok,
Mr. Mopp was right - but I had to remove the Computer class before the searchResult variable for it to work, and make a var type of String, SearchResult. So this works for me below:
String searchResult;
while (!"q".equals(search)) {
searchResult = cpu1.findSys(search);
if (searchResult != null) {
System.out.println(searchResult);
}
else {
System.out.println("not found");
}
You don't want to compare if search == null because search is the user input. You want to check if the result of the search is null:
while (!"q".equals(search)) {
Computer searchResult = cpu1.findSys(search);
if (searchResult != null) {
System.out.println(searchResult);
}
else {
System.out.println("not found");
}
You also should change the return type of findSys to be Computer. Returning just a String limits the usefulness of the function:
public Computer findSys(String c) {
for (int i = 0; i < sysNumbers; i++) {
if (systems[i] != null && systems[i].getCpu().equals(c))
return systems[i];
}
return null;
}
Related
For this program, I'm trying to use Binary searching to find a specific element of a given array, such as title, year, or artist. For now, I'm only testing for title and year since they are both strings. But it seems that for some of the input I put in, the program would return -1, even though the input I put in exists on the array. I'm not sure why this happens.
First is the tester class, second code is the constructor class.
public class TestMusic
{
public static void printMusic(Music[] arr)
{
for (Music music : arr)
{
System.out.println(music.toString());
}
}
public static int binaryTitle(Music[] arr, String title)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
int res = title.compareTo(arr[m].getTitle());
// Check if x is present at mid
if (res == 0)
return m;
// If x greater, ignore left half
if (res > 0)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return -1;
}
public static int binaryArtist(Music[] arr, String artist)
{
int l = 0, r = arr.length - 1;
while (r - l >= 1) {
int m = l + (r-l) / 2;
int res = artist.compareTo(arr[m].getArtist());
if (res == 0)
{
return m;
}
if (res > 0)
{
l = m + 1;
}
else
{
r = m - 1;
}
}
return -1;
}
public static void main(String[]args)
{
Music[] arr = new Music[12];
arr[0] = new Music("Montero", 2021, "Lil Nas X");
arr[1] = new Music("Dynamite", 2020, "BTS");
arr[2] = new Music("Bad Guy", 2019, "Billie Eilish");
arr[3] = new Music("Sicko Mode", 2018, "Travis Scott");
arr[4] = new Music("Shape of You", 2017, "Ed Sheeran");
arr[5] = new Music("Heathens", 2016, "Twenty One Pilots");
arr[6] = new Music("See You Again", 2015, "Wiz Khalifa");
arr[7] = new Music("All About That Bass", 2014, "Meghan Trainor");
arr[8] = new Music("Wrecking Ball", 2013, "Miley Cyrus");
arr[9] = new Music("Paradise", 2011, "Coldplay");
arr[10] = new Music("Shake it Off", 2014, "Taylor Swift");
arr[11] = new Music("Savage", 2021, "Aespa");
System.out.println("Original:");
printMusic(arr);
System.out.println("\nBinary searching Sicko Mode: Index " + binaryTitle(arr, "Sicko Mode"));
System.out.println("\nBinary searching Taylor Swift: Index " + binaryArtist(arr, "Taylor Swift"));
}
}
public class Music
{
// instance variables
private int year;
private String title;
private String artist;
// Constructor for objects of class Music
public Music(String t, int y, String a)
{
// initialize instance variables
title = t;
year = y;
artist = a;
}
public String getTitle()
{
return title;
}
public void setTitle(String t)
{
title = t;
}
public String getArtist()
{
return artist;
}
public void setArtist(String a)
{
artist = a;
}
public int getYear()
{
return year;
}
public void setTitle(int y)
{
year = y;
}
public String toString()
{
String str = String.format( "%-25s %4d %-20s ", title, year , artist);
return str;
}
}
for a binary search to work correctly it must be sorted in some way. If you're searching it by year you need to sort it from smallest to largest. if you're searching it by Title, those Titles must be in some alphabetical order, same with the Artist.
Ex:
{1,4,3,2,5} //searching for 4 returns -1 because it's looking between 3 and 5 and only finding 2.
{1,2,3,4,5} //searching for 4 returns 3 because it looks between 3 and 5 and finds 4 at index 3.
Binary search requires a sorted array. If you use an array that's not sorted, binary search is liable to not find what you need. For this type of thing you need a sequential search.
Example:
[0, 3, 7, 8, 12, 56, 2]
//say you have this array, and you're looking for number 2,
//your function will compare 2 to the middle element: 8.
//2 < 8, so it will throw out everything above 8.
[0, 3, 7]
//Obviously 2 is not there. But it was there originally.
//The problem is it was unsorted
I can confirm that you can only do a type of binary search to its corresponding sort. So title binary search can only happen after a title sort.
I would like to evaluate the length of a phone number string in a setter method. If the phone number is less than or greater than 10 chars a default phone number of "5555555555" is to become the phone number.
package Billing_System;
public class BillingTest
{
public static int current;
public static void main(String[] args)
{
BillingItem Call[] = new BillingItem[10];
Call[0] = new TextMessage(0,"86855536811", "5553381748", 0, 0.00);
Call[1] = new VoiceCall(1, "8685553681", "5553381748", 450, "HIGH",0.00 );
Call[2] = new TextMessage(2, "8685553681", "5553381748", 40, 0.00);
Call[3] = new TextMessage(3, "8685553681", "5553381748", 60, 0.00);
Call[4] = new TextMessage(4, "8685553681", "5553381748", 80, 0.00);
Call[5] = new TextMessage(5, "8685553681", "5553381748", 100, 0.00);
Call[6] = new VoiceCall(6, "8685553681", "5553381748", 2700, "LOW",0.00 );
Call[7] = new VoiceCall(7, "2125551212", "2123381748", 3150, "UNACCEPTABLE",0.00 );
Call[8] = new TextMessage(8, "2125551212", "2123381748", 160, 0.00);
Call[9] = new TextMessage(9, "2125551212", "2123381748", 180, 0.00);
for (BillingItem currentBillingItem: Call)
{
System.out.println(currentBillingItem.toString());
}
}
}
public abstract class BillingItem extends BillingTest
{
public int currentBillingItem;
public String CallerPhNo;
public String DestPhNo;
public BillingItem(String CallerPhNo, String DestPhNo)
{
this.CallerPhNo = CallerPhNo;
this.DestPhNo = DestPhNo;
}
public String getCallerPhNo() //return weight
{
return CallerPhNo;
}
public void setCallerPhNo (String CallerPhNo)
{
if(CallerPhNo.length() != 10)
{
return CallerPhNo = "5555555555";
}
else
{
this.CallerPhNo = CallerPhNo;
}
}
public void setDestPhNo (String DestPhNo)
{
this.DestPhNo = DestPhNo;
}
public String getDestPhNo() //return weight
{
return DestPhNo;
}
public String toString(){
return getCallerPhNo() +" to "+ getDestPhNo();
}
}
Expect Result:
Call 0 - From 5555555555 to 5553381748 was a text message of 0 characters and had a cost 0 TT$.
Actual Result:
Call 0 - From 86855536811 to 5553381748 was a text message of 0 characters and had a cost 0 TT$.
The setter method does not read from a polymorphic input. The user would have to manually input data for the setter method to be initiated upon which the setter method would evaluate the "if" statement.
I think this is what you are asking
if(CallerPhNo.length() != 10)
this.CallerPhNo = "5555555555";
else
this.CallerPhNo = CallerPhNo;
OK as you posted in the comment section that you would love to pass array reference to the method which will in turn change non-fitting numbers to "5555555555" here is possible implementation:
package com.company;
public class Main {
public static void main(String[] args) {
String[] phoneNumbers = {"1234567890", "0123456789", "321", "911", "5678901234"};
verifyNumbers(phoneNumbers);
System.out.println("After verification phone numbers are: ");
for (String s : phoneNumbers)
System.out.println(s);
}
public static void verifyNumbers(String[] numbers){
for (int i = 0; i < numbers.length; i++) {
if (numbers[i].length() != 10)
numbers[i] = "5555555555";
}
}
}
In your case where you have an array of custom Objects you will use appropriate getters and setters in the method (loop) to validate and change number if needed.
All of the program's templates. This was a past assignment but at this point, I'm just trying to understand what's going on.
Under the Apartment class, I'm confused on how to correctly return an array of window orders for one unit, all units, and then the #Override method under ThreeBedroom.
Just for reference of what I've done so far (probably not all correct):
public class Window {
private final int width, height;
public Window(int width, int height) {
this.width = width;
this.height = height;
}
// print text like: 4 X 6 window
public String toString() {
String s = "";
s = width + " x " + height + " window";
return s;
}
// compare window objects by their dimensions
public boolean equals(Object that) {
if (that instanceof Window) {
Window w = (Window) that;
return this.width == w.width && this.height == w.height;
}
else { return false; }
}
}
class WindowOrder {
final Window window; // window description (its width and height)
int num; // number of windows for this order
WindowOrder(Window window, int num) {
this.window = window;
this.num = num;
}
// add the num field of the parameter to the num field of this object
//
// BUT
//
// do the merging only of two windows have the same size
// do nothing if the size does not match
//
// return the current object
WindowOrder add(WindowOrder order) {
if (order.equals(window)) {
this.num -= num;
return order;
}
else {
return order;
}
}
// update the num field of this object by multiplying it with the parameter
// and then return the current object
WindowOrder times(int number) {
WindowOrder window = new WindowOrder(this.window, this.num);
this.num *= number;
return window;
}
// print text like: 20 4 X 6 window
#Override
public String toString() {
String s = "";
s = num + " " + window.toString();
return s;
}
// Two orders are equal if they contain the same number of windows of the same size.
#Override
public boolean equals(Object that) {
if (that instanceof WindowOrder) {
WindowOrder order = (WindowOrder) that;
return this.num == order.num && this.window == order.window;
}
else { return false; }
}
}
public class Room {
Window window;
int numOfWindows;
Room(Window window, int numOfWindows) {
this.window = window;
this.numOfWindows = numOfWindows;
}
WindowOrder order() {
return new WindowOrder(window, numOfWindows);
}
// Print text like: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = numOfWindows + " (" + window.toString() + ")";
return s;
}
// Two rooms are equal if they contain the same number of windows of the same size
#Override
public boolean equals(Object that) {
if (that instanceof Room) {
Room room = (Room) that;
return this.window == room.window && this.numOfWindows == room.numOfWindows;
}
else { return false; }
}
}
class MasterBedroom extends Room {
MasterBedroom() {
super(new Window(4, 6), 3);
}
// Call parent's toString method
//
// return text like: Master bedroom: 3 (4 X 6 window)
#Override
public String toString() {
String s = "";
s = "Master bedroom: " + numOfWindows + " " + window.toString();
return s;
}
}
class GuestRoom extends Room {
GuestRoom() {
super(new Window(5, 6), 2);
}
// Call parent's toString method
//
// return text like: Guest room: 2 (5 X 6 window)
#Override
public String toString() {
String s = "";
s = "Guest room: " + numOfWindows + " " + window.toString();
return s;
}
}
class LivingRoom extends Room {
LivingRoom() {
super(new Window(6, 8), 5);
}
// Call parent's toString method
//
// return text like: Living room: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = "Living room: " + numOfWindows + " " + window.toString();
return s;
}
}
For Apartment's orderForOneUnit() method, I wrote this, but it seems to simplistic and I feel like I should be using a for loop..
WindowOrder[] orderForOneUnit() {
WindowOrder[] order = new WindowOrder[rooms.length];
return order;
}
Am I even close to correctly understanding this? What should be under the Apartment methods?
Didn't looks at the templates but from what you've provided, you're close. All you've done so far is create a WindowOrder[] array of length rooms. You need to add new WindowOrder(desc, num) to these arrays before return order;
/**
* All apartment rooms have the same number of windows, with the
* same size window for each of those.
*/
public class Apartment
{
private int numRooms_;
private int windowsPerRoom_;
private Window window_;
/**
* Constructor
*/
public Apartment(numRooms, windowsPerRoom, desiredWindowHeight, desiredWindowLength)
{
numRooms_ = numRooms;
windowsPerRoom_ = windowsPerRoom;
window_ = new Window(desiredWindowHeight, desiredWindowLenght);
}
/**
* Orders for one room in apartment
*/
public WindowOrder orderForOneUnit()
{
WindowOrder order = new WindowOrder(window_, 1);
return order;
}
/**
* Orders for all rooms in apartment
*/
public List<WindowOrder> orderForAllUnits()
{
List<WindowOrder> orders = new ArrayList<WindowOrder>();
WindowOrder order;
for(i=0; i<numRooms_; i++)
{
orders.add(new WindowOrder(window_, windowsPerRoom_);
}
return orders;
}
}
Now when you're in your code and you're ready for a new Apartment(x, x, x, x) you can do the following (I'll assume you're just in main())
public class ApartmentComplex
{
public static void main(String[] args)
{
int numWindowsPerRoom = 3;
int desiredWindowHeight = 10;
int desiredWindowWidth = 10;
int numRooms = 5;
Apartment aptWithFiveRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
WindowOrder singleSingleOrder = apt.orderForOneUnit();
List<WindowOrder> allRoomsOrder = apt.orderForAllUnits();
numRooms = 3;
Apartment aptWithThreeRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
List<WindowOrder> threeRoomsOrder = apt.orderForAllUnits();
}
}
You do need a for loop. At the moment you are returning an Array where each entry in the array is null.
Here is an example of filling an array:
for (int i = 0; i < array.length; i++) { // iterate over an array
array[i] = getValueFor(i); // put value in the array
}
I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}
I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());