Hi guys i am fairly new to Java but ive come across a problem that i cant seem to fix, the problem is in the 'WashingMachine' Class its not displaying the 'spinSpeed' details , any answers will be appreciated
here are my codes:
enter code here
package test;
public class Client {
private String Name;
private String PhoneNo;
Client () {
Name = null;
PhoneNo= null;
}
Client (String N, String P){
Name = N;
PhoneNo = P;
}
public void setName(String N){
Name = N;
}
public void setPhoneNo(String P) {
PhoneNo = P;
}
public String getName(){
return Name;
}
public String setPhoneNo() {
return PhoneNo;
}
public String toString() {
return "\nName: "+ Name + "\nPhoneNo:"+ PhoneNo.toString();
}
}
enter code here
package test;
public class Machine {
private String Make;
private double Price;
private Client Cust;
public Machine(String make, double price, Client cust)
{
Make = make;
Price = price;
Cust = cust;
}
#Override
public String toString() {
return "\n" +"Make of machine: " + Make + "\n" + "Price: " + Price + "\n" + Cust.toString();
}
public String getMake() {
return Make;
}
public double getprice() {
return Price;
}
public Client getcust() {
return Cust;
}
}
enter code here
package test;
public class WashingMachine extends Machine {
private int spinSpeed;
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
}
#Override
public String toString() {
return "WashingMachine [spinSpeed=" + spinSpeed + ", spinSpeed()=" + spinSpeed() + "]";
}
public int spinSpeed() {
return spinSpeed;
}
enter code here
package test;
import java.util.ArrayList;
public class MachinePurchaseTestVerC {
public static void main(String [] args) {
ArrayList<Machine> gadgets = new ArrayList<Machine> ();
Client mCust2 = new Client("Paul", "0487654321");
Client mCust3 = new Client("Chandra", "0487651234");
Client wCust1 = new Client("Catherine", "0412345678");
Client wCust4 = new Client("Mike", "0412348756");
gadgets.add(new WashingMachine("Bosch", 549.50, wCust1, 3500));
gadgets.add(new Machine("Samsung", 678.50, mCust2));
gadgets.add(new Machine("Electrolux", 449.25, mCust3));
gadgets.add(new WashingMachine("LG", 500.00, wCust4, 3200));
for(int i = 0; i<gadgets.size(); i++){
System.out.println(gadgets.get(i).toString());
System.out.println("----------------------------------");
}
}
}
In your WashingMachine class, you forgot to set the speed in your constructor
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
this.spinSpeed = spinSpeed;
}
hope that helps :)
i get three error message on my BookTest class and it says cannot find symbol on getCode(), getCategory, and calculateTax. how do i fix this? im trying to print these out in a dialog box but these three are the only ones not working.
import javax.swing. JOptionPane;
public class BookTest
{
public static void main(String args[])
{
double charge;
double grandTotal= 0;
String dataArray[][] = {{"NonFiction", "Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99","Haper","NY","US","Political"},
{"NonFiction", "Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX","England", "Historical"},
{"Fiction", "Dracula","Stoker","978-0486411095","5.99","Double Day", "CA","4918362"},
{"NonFiction", "Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY","Transylvania","Historical"},
{"Fiction", "The Mummy","Rice","978-0345369949","7.99","Nelson","GA","3879158"}};
Book bookArray[] = new Book[dataArray.length];
int quantityArray[] = {12, 3, 7, 23, 5};
for (int i = 0; i < dataArray.length; i++)
{
if (dataArray[i][0] == "NonFiction")
{
bookArray[i] = new NonFictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), dataArray[i][7], dataArray[i][8]);
}
else
{
bookArray[i] = new FictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), Integer.parseInt(dataArray[i][7]));
}
}
String msg = "";
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
grandTotal = charge + grandTotal;
msg += String.format("%s %s %d $%.2f $%.2f\n", bookArray[i].getTitle(), bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax, charge); //this is where i get the 3 error messages. im trying to print all in one dialog box the title, category of the book, charge and tax for each book.
}
msg += String.format("Grand Total $%.2f ", grandTotal);
JOptionPane.showMessageDialog(null, msg);
}
}
**************************************************************
public abstract class Book implements Tax
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;
public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}
public Book(String t, String a, String i, double p, Publisher n)
{
setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setAuthor(String a)
{
author = a;
}
public String getAuthor()
{
return author;
}
public void setIsbn(String i)
{
isbn = i;
}
public String getIsbn()
{
return isbn;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void setPublisher(Publisher n)
{
publisher = n;
}
public Publisher getPublisher()
{
return publisher;
}
public abstract double calculateTotal(int quantity);
public double calculateTax(double a)
{
return a * .08;
}
public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}
}
********************************************************
public class NonFictionBook extends Book
{
private String country;
private String category;
public NonFictionBook()
{
super();
setCountry("");
setCategory("");
}
public NonFictionBook(String t, String a, String i, double p, Publisher n, String c, String ca)
{
super(t,a,i,p,n);
setCountry(c);
setCategory(ca);
}
public void setCountry(String c)
{
country = c;
}
public void setCategory(String ca)
{
category = ca;
}
public String getCountry()
{
return country;
}
public String getCategory()
{
return category;
}
public String toStirng()
{
return( super.toString() + "Country " + country + " Category " + category);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if( country != "US" )
charge += 50;
return charge;
}
}
*********************************************
public class FictionBook extends Book
{
private int code;
public FictionBook()
{
super();
setCode(0);
}
public FictionBook(String t, String a, String i, double p, Publisher n, int c)
{
super(t,a,i,p,n);
setCode(c);
}
public void setCode(int c)
{
code = c;
}
public int getCode()
{
return code;
}
public String toString()
{
return (super.toString() + " Code " + code);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if (quantity > 5)
charge += 5 * (quantity - 5);
return charge;
}
}
The tree methods are implemented in subclasses of Books. So you have to cast the value to the subclass.
if (bookArray[i] instanceof FictionBook){
FictionBook fb = (FictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", fb.getTitle(), "", fb.getCode(), 0, charge);
}
if (bookArray[i] instanceof NonFictionBook){
NonFictionBook fb = (NonFictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", nfb.getTitle(), nfb.getCategory(), nfb.getCode(), nfb.calculateTax, charge);
}
and so on
Also you have to use equals() for comparing string. Not ==
In the line you get error you try to print fields that are not instances of the Book class but of its subclasses.
You got an array of Books, you iterate on them and try to print the information. But not all the Books have getCode() method (only the fiction books) and only the non fiction books have getCategory() method. So you can't do this for ALL books.
You can change your print depending on the book type or you can make a method in Book class and each subclass can override it that prints the information you have for this class (like the toString method). Then use that in the main class.
And also as pointed in comments test if strings are equal with equals operator and not == or !=
Your array uses the type book:
Book bookArray[] = new Book[dataArray.length];
Later, you add sub-classes into this array, like NonFictionBook. Since code, category etc. are only part of the sub-classes, you cannot access them using the Book array reference.
// won't work because class Book does not have these methods, properties
bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax
You need to cast the object (based on what type is in the array).
I have this main java file:
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
// REPLACEME
}
I want to call and be able to use getDiscount() and etc from the "Item" subclass, but I can't figure out how to access it in a different file + class that extends GroceryBill.
public class DiscountBill extends GroceryBill {
private int myCount;
private double myDiscount;
private double myPrice;
private String myName;
public DiscountBill(Employee clerk, boolean preferred) {
super(clerk);
String name = "";
double price = 0;
double discount = 0;
GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
Object myItem = new Item(name, price, discount);
myDiscount = myBill.getDiscount();
myPrice = ((GroceryBill.Item) myItem).getPrice();
if (preferred && myDiscount > 0.0) {
myCount++;
}
}
public int getDiscountCount() {
return myCount;
}
public double getDiscountAmount() {
return myDiscount;
}
public double getDiscountPercent() {
return (myPrice / getDiscountCount()) * 100;
}
}
Here is my class that is in a different java file that extends the original one. How would I call methods from the Item subclass that belongs to the GroceryBill class?
You can do like
Create object to super class using that object try to create object for its sub class.
for example:
public class Sample {
class InnerClass
{
public void foo()
{
System.out.println("Helolo");
}
}
}
Base class is :
public class BaseClass extends Sample {
public static void main(String[] args) {
Sample sObj = new Sample();
Sample.InnerClass innerObj = sObj.new InnerClass();
innerObj.foo();
}
}
You can follow this approach to call inner class methods
To access inner static classes :
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
In your case just add statement like :
GroceryBill.Item = new GroceryBill.Item(name, price, discount);
I am trying to verify what is wrong with my class builds to make address class communicate with my warehouse class. My get() and set methods along with toString() is in question. Any help would be greatly appreciated
public class Address
{
private String street;
private String city;
private String state;
private int zip;
public Address()
{
setStreet("");
setCity("");
setState("");
setZip(0);
}
public Address(String str, String c, String sta, int z)
{
setStreet(str);
setCity(c);
setState(sta);
setZip(z);
}
public String getStreet()
(
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public int getZip()
{
return zip;
}
public void setStreet( String str)
{
street = str;
}
public void setCity( String c)
{
city = c;
}
public void setState( String sta )
{
state = sta;
}
public void setZip( String z )
{
zip = z;
}
public String toString()
{
return( " Street " + street + " City " + city +" State " + state + " Zip " + zip);
}
}
Must communicate with the following warehouse class:
public class Warehouse
{
private double squareFeetSize;
private double pricePerSquareFoot;
private int televisions;
private int computers;
private Address address;
public Warehouse()
{
setSquareFeetSize(0.0);
setPricePerSquareFoot(0.0);
setTelevisions(0);
setComputers(0);
setAddress(new Address());
}
public Warehouse( double s, double p, int t, int c, Address a)
{
setSquareFeetSize(s);
setPricePerSquareFoot(p);
setTelevisions(t);
setComputers(c);
setAddress(a);
}
public double getSquareFeetSize()
{
return squareFeetSize;
}
public double getPricePerSquareFoot()
{
return pricePerSquareFoot;
}
public int getTelevisions()
{
return televisions;
}
public int getComputers()
{
return computers;
}
public Address getAddress()
{
return address;
}
public void setSquareFeetSize( double s)
{
squareFeetSize = s;
}
public void setPricePerSquareFoot ( double p )
{
pricePerSquareFoot = p;
}
public void setTelevisions ( int t )
{
televisions = t;
}
public void setComputers ( int c)
{
computers = c;
}
public void setAddress( Address a)
{
address = a;
}
public String toString()
{
return (" Square Foot Size " + squareFeetSize + " Price Per Square Foot " +
pricePerSquareFoot + " Televisions " + televisions + " Computers " +
computers + " Address " + address.toString());
}
public double calculateWarehouseCharge()
{
double charge = 0.0;
charge = (squareFeetSize * pricePerSquareFoot + (2.25 * televisions) + (5.50 * computers));
return charge;
}
public double purchaseTelevision( int quantity, double price)
{
double cost = 0.0;
if( quantity > televisions)
{
JOptionPane.showMessageDialog(null, "Television Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
televisions = televisions - quantity;
}
return cost;
}
public double purchaseComputer( int quantity, double price)
{
double cost = 0.0;
if( quantity > computers)
{
JOptionPane.showMessageDialog(null, "Computer Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
computers = computers - quantity;
}
return cost;
}
}
class Address{
private street = "123 Lame Street";
public getStreet(){
return street;
}
}
class Warehouse{
Address address = new Address(); // create an instance; not just declare
public void shipping(){
shipTo(address.getStreet()); // Here's how to "communicate"
}
}
You are on correct way. Your code is working. Because ToString is method of Object class that you overwrite in your class. http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html
Are you not getting correct result ?
I have no idea why our professor is making us do this weird printing but its for our final, its due in an hour, and ive been trying to get it to run forever and I cant get anywhere. So i have four classes, MyWord, Section, Page and Newspaper. MyWord is just Myword. Section contains Section and MyWord. Page includes Section, Page, and MyWord. Newspaper contains them all. I have a main method that just prints off the info you type in. Here is the only example provided. All of my code is included from the classes to show I've actually done work and need help. thank you.
Word[] w = new Word[3]; //example
w[0] = new Word(“hello”);
w[1] = new Word(“bob”);
w[2] = new Word(“smith”);
Section s = new Section(w, 20);
s.print();
//the above call to print should print off the following or something
//very similar to the following:
//Section 20: hello bob smith
my classes are also here
public class MyWord
{
private String word;
public MyWord(){ //constructor
word = "";
}
public MyWord(String word){ //using this keyword to assign word
this.word=word;
}
public String getWord(){ //accessor
return word;
}
public void setWord(String word){ //mutator
this.word=word;
}
public void print(){
System.out.print(word);
}
}
public class Section
{
private MyWord[] words; //taking in MyWord
private int sectionNumber;
public Section(){ //default constructor
words = new MyWord[0];
sectionNumber = 0;
}
public Section(MyWord[] m, int num){ //constructor
words = m;
sectionNumber = num;
}
public int getSectionNumber(){ //accessor
return sectionNumber;
}
public void setSectionNumber(int num){ //mutator
sectionNumber = num;
}
public MyWord[] getWords(){ //accessor
return words;
}
public void setWords(MyWord[] m){ //mutator
words = m;
}
public void print(){
System.out.print("Section " + sectionNumber + ": ");
for(int i =0; i <words.length; i++){
words[i].print();
System.out.print(" ");
}
}
}
public class Page
{
private Section[] sections; //taking in other class
private int pageNumber;
public Page(){ //setting defaults
sections = new Section[0];
pageNumber = 0;
}
public Page(Section[] m, int num){ //passing in sections[]
sections = m;
pageNumber = num;
}
public int getPageNumber(){ //accessor
return pageNumber;
}
public void setPageNumber(int num){ //mutator
pageNumber = num;
}
public Section[] getSections(){ //accessor
return sections;
}
public void setSections(Section[] m){ //mutator
sections = m;
}
public void print(){
System.out.print("Page " + pageNumber + ": ");
for(int i =0; i <sections.length; i++){
sections[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
public class Newspaper
{
private Page[] pages; //taking in Page[]
private String title;
private double price;
public Newspaper(){
pages = new Page[0];
title = "Comp Sci Newspaper"; //default title
price = 2.50; //default price
}
public Newspaper(Page[] m, double num, String t){
pages = m;
price = num; //assigning values
title = t;
}
public String getTitle(){ //accessor
return title;
}
public void setTitle(String t){ //mutator
title = t;
}
public Page[] getPages(){ //accessor
return pages;
}
public void setPages(Page[] m){ //mutator
pages = m;
}
public double getPrice(){ //accessor
return price;
}
public void setPrice(double num){ //mutator
price = num;
}
public void print(){
System.out.print("Newspaper " + title + " " + "Price: " + price);
for(int i =0; i <pages.length; i++){
pages[i].print();
System.out.print(" ");
}
System.out.println(" ");
}
}
I think you should be making your array as MyWord not Word, so :
MyWord[] w = new MyWord[3];
Then as far as I can see it might work? Can you say what happens when you try to run / compile it?