Java not showing the output im looking for (Beginner) - java

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 :)

Related

Using toString() method from child class

Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?
The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}

Making a class-array dynamic in Java

I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

Java search method between objects using scanner

I am trying to make a program in java oop in which I create some persons in the main (every person has a name, an age, a status: employed or not).
I want to search these persons by name and display all the details.
For example if a have a person named John and I find it by name, I want to list all the details (status, age and so on).
I tried to implement this method in Person class.
I don t know if is better to create a map which contains all the persons and the name and then to search in it.
Below is my code:
Person CLASS:
package app;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Person extends Employed {
Scanner scan = new Scanner(System.in);
private String name;
private int age;
private int kids;
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 int getKids() {
return kids;
}
public void setKids(int kids) {
this.kids = kids;
}
public Person(){
System.out.println("************************************************************");
}
public void displayPerson(){
if(super.getPeriod()==0 && super.getUnemploymentBenefit()==0){
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is employed" + "\nWorking Place: " + super.getWorkingPlace()
+ "\nSallary: " + df.format(super.getSallary()) + " EUR per year" + "\nWorking Time: " + super.getHours() + " hours per day");
}else
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is unemployed" +"\nUnemployment Time: " + Math.round(super.getPeriod())
+ "\nUnemployment Benefit: " + df.format(super.getUnemploymentBenefit()) + " EUR per year");
}
public void searchMethod(){
System.out.println("Are you looking for someone?");
String s = scan.nextLine();
if(s==name) {
System.out.println("Here are all the details about the person you are looking for: ");
}
}
}
Employed CLASS:
package app;
import java.text.DecimalFormat;
public class Employed extends Unemployed {
DecimalFormat df = new DecimalFormat("0.000");
private String WorkingPlace;
private double sallary;
private double hours;
public String getWorkingPlace() {
return WorkingPlace;
}
public void setWorkingPlace(String WorkingPlace) {
this.WorkingPlace = WorkingPlace;
}
public double getSallary() {
return sallary;
}
public void setSallary(double sallary) {
this.sallary = sallary;
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
this.hours = hours;
}
}
Unemployeed CLASS:
package app;
public class Unemployed{
private double period;
private double UnemploymentBenefit;
public double getPeriod() {
return period;
}
public void setPeriod(double period) {
this.period = period;
}
public double getUnemploymentBenefit() {
return UnemploymentBenefit;
}
public void setUnemploymentBenefit(double UnemploymentBenefit) {
this.UnemploymentBenefit = UnemploymentBenefit;
}
}
Program CLASS:
package app;
public class Program extends Person{
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("John Doe");
p1.setAge(47);
p1.setKids(3);
p1.setWorkingPlace("IKEA");
p1.setSallary(12.500);
p1.setHours(12.5);
p1.displayPerson();
p1.searchMethod();
Person p2 = new Person();
p2.setName("Snow Tiffany");
p2.setAge(27);
p2.setKids(0);
p2.setPeriod(15.9);
p2.setUnemploymentBenefit(7.000);
p2.displayPerson();
}
}
First you should add a construtor.
Then you can create an object from class Person like this:
Person p1 = new Person("John Doe", 47,3, "IKEA", 12.500, 12.5);
String personInfo = p1.get(..) + p1.get(..);
System.out.println(personInfo);
Your code is a bit desorganized. Java classes should have constructors. Variables, in general, starts with lowerCase character.

Need help making a relationship work with (2) classes

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 ?

Array sorting printing and summing

What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));

Categories