The values from expected output are not showing - java

I instantiated the SpaceStation class and called addAstronaut method but the name, weight, altitude, and astronauts are not showing in my output when I run it.
SpaceStation.java:
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Astronaut[] Astronauts;
private int totalAstronauts;
//overloaded constructor
public SpaceStation(String name, double
weight) {
int altitude = 0;
int totalAstronauts = 0;
}
//method
public void addAstronaut(String name, double
height, double weight) {
Astronauts = new Astronaut[3];
stationWeight = stationWeight + weight;
totalAstronauts++;
}
public double setAltitude(double altitude) { return this.altitude = altitude; }
public String toString() {
return "SpaceStation: " + name + "\n" +
"Weight(kg): " + stationWeight + "\n" +
"Altitude(km): " + (altitude) + "\n" +
"Astronauts: " + (totalAstronauts);
}
public static void main(String[] args) {
SpaceStation aa = new SpaceStation("ISS", 419700.0);
System.out.println(aa);
aa.addAstronaut("Eli", 167.64, 81.65);
aa.addAstronaut("John", 185.43, 100.30);
aa.addAstronaut("Joey", 175.38, 90.38);
aa.setAltitude(400.0);
}
}

Your code contains four errors:
1- You are not setting the content of the instance variable name in the constructor. This causes the line SpaceStation: null when printing the output. You need to set the name in the constructor. Change the constructor to be like this:
public SpaceStation(String name, double
weight) {
this.name = name; // This line was added
int altitude = 0;
int totalAstronauts = 0;
}
2- You are printing the content of ss before adding your astronauts and setting the altitude. At that time, there are no astronauts added, so it's normal that the weight, number of astronauts and altitude is 0. If you print the content of the space station after doing those operations, it's going to work:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss); // This line was moved after the addAstronaut and setAltitude methods.
}
3- As #sagi flagged, in the constructor, you're declaring and initializing another variable than in your class, but with the same name. Technically, doubles and integers are already initialized with 0.0 so you don't really notice it, but the variables altitude and totalAstronauts in your constructor are useless as they are. Suggesting to update the constructor like this:
public SpaceStation(String name, double
weight) {
this.name = name;
altitude = 0; // Removed "int"
totalAstronauts = 0; //Removed "int"
Astronauts = new Astronaut[3];
}
4- As #sagi flagged, you're re-initializing the Astronaut array every time you add an astronaut. You need to initialize it in the constructor once, and presumably set the astronauts in the array every time you add one.
With all of those comments, the SpaceStation class should look like this:
package gov.nasa.spacevehicles;
import gov.nasa.personnel.Astronaut;
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Astronaut[] Astronauts;
private int totalAstronauts;
//overloaded constructor
public SpaceStation(String name, double
weight) {
this.name = name;
altitude = 0;
totalAstronauts = 0;
Astronauts = new Astronaut[3];
}
//method
public void addAstronaut(String name, double
height, double weight) {
Astronauts[totalAstronauts] = new Astronaut(name, height, weight);
stationWeight = stationWeight + weight;
totalAstronauts++;
}
public double setAltitude(double altitude) { return this.altitude = altitude; }
public String toString() {
return "SpaceStation: " + name + "\n" +
"Weight(kg): " + stationWeight + "\n" +
"Altitude(km): " + (altitude) + "\n" +
"Astronauts: " + (totalAstronauts);
}
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss);
}
}

(1) The constructor of SpaceStation does not set the passed in values of name and weight to the parameters of the SpaceStation object. Add this.name = name and this.stationWeight = weight to the constructor. The this keyword tells Java that the variable you are referring to is the parameter of the object that the constructor is being called for.
The constructor also creates new variables named altitude and totalAstronauts that exist only inside of the constructor. To change the values of the parameters of the object the constructor is called for, add this.altitude = altitude and this.totalAstronauts = totalAstronauts to the constructor.
//overloaded constructor
public SpaceStation(String name, double weight) {
this.altitude = 0;
this.totalAstronauts = 0;
this.name = name;
this.stationWeight = weight;
}
(2) Your main method prints ss before you perform operations on it. Place it after the other code in your main:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss);
}
(3) The Astronauts array is overwritten every time addAstronaut() is called. Fix this by creating and adding a new Astronaut instance to the Astronauts array in addAstronaut(). You should add a line to the constructor to initialize the array to an empty array of a size of 3 or greater so there is space to add Astronaut objects in addAstronaut().
//overloaded constructor
public SpaceStation(String name, double weight) {
this.altitude = 0;
this.totalAstronauts = 0;
this.name = name;
this.stationWeight = weight;
// Add this line
Astronauts = new Astronaut[10];
}
//method
public void addAstronaut(String name, double height, double weight) {
// Adds a new Astronaut object to the array at index totalAstronauts
Astronauts[totalAstronauts] = new Astronaut(name, height, weight);
stationWeight = stationWeight + weight;
totalAstronauts++;
}

There are mainly 2 errors due to which name is been shown has null.
1: You haven't set name in your constructor, Which resulted in name having a default value of null.
So when you say this.name = name it tells that I have this in me, please look and set its value.
//overloaded constructor
public SpaceStation(String name) {
this.name = name; // changed
int altitude = 0;
Astronauts = new Astronaut[3];
int totalAstronauts = 0;
}
Also in the main function, you were trying to print it before setting the values for it.
You should have first given the values for it and then print it.
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss); // changed
}
Additionally, I see you have made an Astronaut[] Astronauts array but never added any Astronauts in it. So what's the whole point of it?
When you were adding Astronauts it only stored the total numbers of astronauts but never an actual Astronauts Object.
//method
public void addAstronaut(String name, double
height, double weight, Astronaut object) {
Astronauts[totalAstronauts] = object; // changed
stationWeight = stationWeight + weight;
totalAstronauts++;
}
Main:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS");
ss.addAstronaut("Smith", 167.64, 81.65, new Astronaut("Smith", 167.64, 81.65));
ss.addAstronaut("John", 185.43, 100.30, new Astronaut("John", 185.43, 100.30));
ss.addAstronaut("Joey", 175.38, 90.38, new Astronaut("Joey", 175.38, 90.38));
ss.setAltitude(400.0);
System.out.println(ss);
// (Added) Printing astronauts from array
for(Astronaut a : ss.Astronauts) {
System.out.println(a);
}
}
Astronaut class:
public class Astronaut {
//private fields
private String name;
private double height;
private double weight;
//defualt constructor
public Astronaut() { }
//overloaded constructor
public Astronaut (String name, double height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
// Added
public String toString() {
return "\nAstronaut Name: "+name+"\n"+name+" Height: "+height+"\n"+name+" Weight: "+weight;
}
}
Output:
SpaceStation: ISS
Weight(kg): 272.33
Altitude(km): 400.0
Astronauts: 3
Astronaut Name: Smith
Smith Height: 167.64
Smith Weight: 81.65
Astronaut Name: John
John Height: 185.43
John Weight: 100.3
Astronaut Name: Joey
Joey Height: 175.38
Joey Weight: 90.38

Related

How can I declare an array in one function and use that same array in another function?

Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?

Java simple commission program, return data based on search (JOptionPane)

I'm creating a simple commission program with the data of the sales people already in the code. I just want to find a way to search for a NAME and return their name total salary. I've hit a roadblock for the past few hours trying to do this.
public class SalesPeople {
String personName;
double annualSalary;
double salesAmount;
double percentComission;
public SalesPeople(String xPersonName, double xAnnualSalary, double xSalesAmount, double xPercentComission) {
personName = xPersonName;
annualSalary = xAnnualSalary;
salesAmount = xSalesAmount;
percentComission = xPercentComission;
}
double totalSalary = annualSalary + (salesAmount * percentComission);
public String getPersonName() {
return personName;
}
public double getAnnualSalary() {
return annualSalary;
}
public double getSalesAmount() {
return salesAmount;
}
public double getPercentComission() {
return percentComission;
}
public double getTotalSalary() {
return totalSalary;
}
}
In the last few lines of the class below are where I'm having trouble.
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class CommissionCalc {
public static void main (String [] args ) {
ArrayList<SalesPeople> salesList = new ArrayList<SalesPeople>();
// PersonName, AnnualSalary, SalesAmount, PercentComission
SalesPeople salesPerson1 = new SalesPeople ("Bob", 30000, 5000, .09);
SalesPeople salesPerson2 = new SalesPeople ("Jane", 40000, 7000, .10);
salesList.add(salesPerson1);
salesList.add(salesPerson2);
String userInput;
userInput = JOptionPane.showInputDialog("Enter the name of a sales person:");
if((salesList.get(0).getPersonName()).equals(userInput)) {
for (int cnt = 0; cnt < salesList.size(); cnt++) {
if((salesList.get(cnt).getPersonName()).equals(userInput)) {
System.out.println(salesList.get(cnt).getPersonName() + salesList.get(cnt).getTotalSalary());
}
}
}
}
}
}
}
The name prints, but I'm getting a return of 0.0 on total salary. I just can't get it to return the Name and TotalSalary. Any help would really be appreciated.
You need to use System.out.println(salesList.get(cnt).getPersonName()); instead of System.out.println(salesList.get(cnt));. For name and total salary use code like this:
System.out.println("Person name: " + salesList.get(cnt).getPersonName() + ", Total salary: " + salesList.get(cnt).getPersonName().getTotalSalary());
For total salary, replace your getTotalSalary() method with this code:
public double getTotalSalary() {
return getAnnualSalary() + (getSalesAmount() * getPercentComission());
}
Try to set totalSalary in SalesPeople constructor. So the code would be:
public class SalesPeople {
String personName;
double annualSalary;
double salesAmount;
double percentComission;
double totalSalary;
public SalesPeople(String xPersonName, double xAnnualSalary, double xSalesAmount, double xPercentComission) {
personName = xPersonName;
annualSalary = xAnnualSalary;
salesAmount = xSalesAmount;
percentComission = xPercentComission;
totalSalary = annualSalary + (salesAmount * percentComission);
}
...
}
Before SalesPeople class initialization, the default value for annualSalary, salesAmount and percentComission are 0 (or null as undefined).If you define totalSalary outside constructor, totalSalary will always be 0.
The alternative solution would be: define a setTotalSalary() method in your SalesPeople class, and call it after you create a SalsePeople instance.
public void setTotalSalary(){
totalSalary = this.annualSalary + (this.salesAmount * this,percentComission);
}
And call setTotalSalary() you define a SalesPeople instance.
SalesPeople salesPerson1 = new SalesPeople ("Bob", 30000, 5000, .09);
salesPerson1.setTotalSalary();

ArrayList. ArrayList to int and double

I have the problem that I can't take a number from the arraylist and make it into a int or double which I have to do to cacluate the BMI using weight and height. Please have a look!
The assignment is to put in guests' weight, length, and name and sort the ones with a bad length to height ratio out. In the main I create an array with a couple of guests and when I run it says:
"Exception in thread "main" java.lang.NumberFormatException: For input string "name"
and
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Diet.putOnDiet(Diet.java:12)
at TestDiet.main(TestDiet.java:7)
The Diet class is as follows:
public class Diet{
public static ArrayList<Guest> putOnDiet(ArrayList <Guest> list){
ArrayList<Guest> namn = new ArrayList<Guest>();
ArrayList<Guest> hej = new ArrayList<Guest>();
for(int i = 0; i<=list.size()/3; i = i+3){
int langd = Integer.parseInt(list.get(i+1).toString()); //I dont know how to make this work
double vikt = Double.parseDouble(list.get(i).toString());
String name = list.get(i+2).toString();
if ((vikt) > 1.08*(0.9*(langd -100))){
namn.add(new Guest(vikt, langd, name));
}
}
return namn;
}
}
And the Guest class:
public class Guest {
private double weight; private double length; private String name;
public Guest(double weight, double length, String name){
this.name = name; this.weight = weight; this.length = length; // Maybe the problem is here. How do you modify the class to make it work?
}
public String getName() {
return name;
}
public double getWeight()
{
return weight;
}
public double getLength() {
return length;
}
public void setName(String name) {
this.name = name;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setLength(double length)
{ this.length = length;
}
public boolean isSlim() {
if (weight >= 1.08 * 0.9 * (length - 100)) {
return false;
}
else
return true;
}
public String toString() {
return name + "\n" + weight + "\n" + length;
}
}
Are you sure that the you are parsing an integer?
Well number parsing exception is thrown when it can't parse the number. When the string is not a number like "somthing#$%^&". So try replacing this line
int langd = Integer.parseInt(list.get(i+1).toString());
with this
try {
int langd = Integer.parseInt(list.get(i+1).toString());
} catch (NumberFormatException e) {
System.out.println(list.get(i+1).toString() +" : This is not a number");
System.out.println(e.getMessage());
}
EDIT After reading WOUNDEDStevenJones answer I also think you should not be even using toString() or parsing methods. See WOUNDEDStevenJones answer for more details.
It looks like you'll want to change it to
for (int i=0; i<list.size(); i++) {
double langd = list.get(i).getLength();
double vikt = list.get(i).getWeight();
String name = list.get(i).getName();
}
and kind of ignore your getString() method for this purpose
Note: I'm not sure what you're trying to do with your different indexes, but they'll probably all be .get(i)
The method list.get(i) will return an object of type Guest. Guest has methods, getWeight() and getLength().
list.get(i).getWeight()
This would actually give you a double value in return.
And,
Integer.parseInt(list.get(i).getWeight().toString())
This should be able to parse.
Hope this helps.
_san

Data validation to an throw exception

I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep

Can't implement methods in Subclasses from interface

I know this is homework so this may sound weird. Right now I am trying to get rid of a compile error saying pool must implement abstract methods. Pool is implemented by the BackYard interface, while deck is a subclass of pool and bollards is a subclass of deck. I am not allowed to change the code in the display output method in the driver class and I am not allowed to change code in deck or bollards. The compiler keeps insisting that I recode all the subclass methods in pool or make pool abstract which I can't do either. What exactly do I need to fix. Also let me know if I really needed to code all the get methods in the Backyard interface
Here is the driver class:
public class YardOrders
{
//Constants
final static int POOL_ONLY = 1;
final static int POOL_N_DECK=2;
final static int POOL_DECK_N_BOLLARD=3;
final static int DISPLAY_ORDERS=4;
final static int DEFAULT_INT=0;
//Methods
public static void main(String[] args)
{
int numberOfOrders=DEFAULT_INT;
BackYard backYard[] = new BackYard[100];
int selection = DEFAULT_INT;
do
{
selection = Integer.parseInt(JOptionPane.showInputDialog(null,
"Options:\nEnter "+ POOL_ONLY +" for a pool.\n" +
"Enter "+ POOL_N_DECK +
" for a pool and a concrete " +
"deck surrounding the pool.\n"+
"Enter "+POOL_DECK_N_BOLLARD+" for a pool," +
" deck, and bollards.\n"+
"Enter "+DISPLAY_ORDERS+" to display orders and exit.",
"Pool Options", JOptionPane.PLAIN_MESSAGE));
if(selection > DEFAULT_INT && selection < DISPLAY_ORDERS)
{
getPoolInput(backYard,numberOfOrders,selection);
numberOfOrders++;
System.out.println(numberOfOrders);
}
else if(selection==DISPLAY_ORDERS)
{
displayOrders(backYard,numberOfOrders);
System.out.println(numberOfOrders);
System.exit(DEFAULT_INT);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid input. Values" +
" must be between 1 and 4.");
}
}while(selection != DISPLAY_ORDERS);
}
private static void getPoolInput(BackYard backYard[],int numberOfOrders,int selection)
{
//Pool attributes
String lastName = JOptionPane.showInputDialog(null,
"Enter last name.\n","Last Name",
JOptionPane.PLAIN_MESSAGE);
String firstName = JOptionPane.showInputDialog(null,
"Enter first name.","First Name",
JOptionPane.PLAIN_MESSAGE);
double poolDepth = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool depth in inches.","Pool Depth",
JOptionPane.PLAIN_MESSAGE)); //In inches.
double poolDiameter = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool diameter in feet.","Pool Diameter",
JOptionPane.PLAIN_MESSAGE));//In feet.
if(selection == POOL_ONLY)
{
//Pool instantiation.
backYard[numberOfOrders]= new Pool(lastName,firstName,
poolDepth,poolDiameter);
}
else
{
getDeckInput(backYard,
numberOfOrders,selection,
lastName,firstName,
poolDepth, poolDiameter);
}
}//End of method
private static void getDeckInput(BackYard[] backYard,
int numberOfOrders, int selection,
String lastName, String firstName,
double poolDepth, double poolDiameter)
{
//Deck attributes
double deckLength=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck length in feet.","Deck Length",
JOptionPane.PLAIN_MESSAGE));
double deckWidth= Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck width in feet.","Deck Width",
JOptionPane.PLAIN_MESSAGE));
if(selection==POOL_N_DECK)
{
backYard[numberOfOrders]= new Deck(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
else
{
getBollardInput(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
}
public static void getBollardInput(String lastName, String firstName,
double poolDepth, double poolDiameter,
double deckLength, double deckWidth)
{
//Bollard attributes
double bollardHeight=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard height in inches.","Bollard Height",
JOptionPane.PLAIN_MESSAGE));
double bollardDiameter=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard diameter in incehs.","Bollard Diameter",
JOptionPane.PLAIN_MESSAGE));
int numberOfBollards=Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter the number of bollards.","Number of bollards",
JOptionPane.PLAIN_MESSAGE));
//Bollard instantiation
Bollards bollards= new Bollards(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth,
bollardHeight, bollardDiameter,
numberOfBollards);
}
private static void displayOrders(BackYard[] orders, int numberOfOrders)
{
DecimalFormat dec3 = new DecimalFormat("0.000");
String divider = "******************************************************" +
"***********\n";
JTextArea textOut = new JTextArea(divider, 10, 30);
JScrollPane scroller = new JScrollPane(textOut);
for(int sub = 0; sub < numberOfOrders; sub++)
{
textOut.append("Customer Name: " + orders[sub].getLastName() + ", ");
textOut.append(orders[sub].getFirstName() + "\n");
textOut.append("Pool Depth:" +
dec3.format(orders[sub].getInsideDepth()) + "\n");
textOut.append("Pool Diameter: "+
dec3.format(orders[sub].getInsideDiameter()) + "\n");
textOut.append("Deck Width: " +
dec3.format(orders[sub].getDeckWidth()) + "\n");
textOut.append("Deck Length: " +
dec3.format(orders[sub].getDeckLength()) + "\n");
textOut.append("Number of Bollards Ordered: " +
orders[sub].getNumberOfBollards() + "\n");
textOut.append("Height of Bollards: " +
dec3.format(orders[sub].getBollardHeight()) + "\n");
textOut.append("Diameter of Bollards: " +
dec3.format(orders[sub].getBollardDiameter()) + "\n");
textOut.append("Cubic Yards of Concrete Needed: " +
dec3.format(orders[sub].getConcreteVolume()) + "\n");
textOut.append(divider);
} // end for loop
JOptionPane.showMessageDialog(null, scroller, "Orders Placed",
JOptionPane.PLAIN_MESSAGE);
} // end method DisplayOrders*/
}
Here is the BackYard interface:
public interface BackYard
{
//Universal constants
public static final int CU_IN_TO_CU_YD = 46656;
public static final int FT_TO_IN = 12;
public static final double DENSITY = 3.75; // in inches
//Pool constants.
public static final String DEFAULT_NAME = "Unknown";
public static final int DEFAULT_DIAM_DEPTH = 0;
public static final int STANDARD_DEPTH = 24; // in inches
public static final int STANDARD_DIAMETER = 6; // in feet
public static final int MIN_DEPTH = 10; // in inches
public static final int MAX_DEPTH = 72; // in inches
public static final int MIN_DIAMETER = 3; // in feet
public static final int MAX_DIAMETER = 25; // in feet
//Deck constants
public final static double MAX_DECK_LENGTH = 50.0; // in feet
public static final double MAX_DECK_WIDTH = 50.0; // in feet
public static final int DEFAULT_WIDTH_AND_LENGTH = 0;
//Bollard constants
public static final double MAX_BOLLARD_HEIGHT = 60.0; // in inches
public static final double MIN_BOLLARD_HEIGHT = 24.0; // in inches
public static final double MAX_BOLLARD_DIAMETER = 18.0; // in inches
public static final double MIN_BOLLARD_DIAMETER = 3.0; // in inches
public static final int MIN_NUMBER_OF_BOLLARDS = 4; // units
//Methods.
public abstract String getLastName();
public abstract String getFirstName();
public abstract double getInsideDepth();
public abstract double getInsideDiameter();
public abstract double getDeckWidth();
public abstract double getDeckLength();
public abstract int getNumberOfBollards();
public abstract double getBollardHeight();
public abstract double getBollardDiameter();
public abstract double getConcreteVolume();
}
Here is the pool class
public class Pool implements BackYard
{
// instance variable(s)
private double insideDiameter; // in feet
private double insideDepth; // in inches
private String lastName;
private String firstName;
// class variable(s)
public static int numberOfOrders;
// Zero argument constructor. Sets instance variables to default values
public Pool()
{
setInsideDiameter(DEFAULT_DIAM_DEPTH);
setInsideDepth(DEFAULT_DIAM_DEPTH);
setLastName(DEFAULT_NAME);
setFirstName(DEFAULT_NAME);
}
// Two parameter constructor.
// Sets names to input values and measurements to standard values
public Pool(String lastNameIn, String firstNameIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(STANDARD_DEPTH);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets names and depth to input values and diameter to standard value
public Pool(String lastNameIn, String firstNameIn, double depthIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets all instance variables to input values
public Pool(String lastNameIn, String firstNameIn, double depthIn,
double diameterIn)
{
setInsideDiameter(diameterIn);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// returns depth
public double getInsideDepth()
{
return insideDepth;
}
// validates input and sets depth
public void setInsideDepth(double inDepth)
{
insideDepth = ((inDepth >= MIN_DEPTH &&
inDepth <= MAX_DEPTH) ? inDepth : DEFAULT_DIAM_DEPTH);
}
// returns diameter
public double getInsideDiameter()
{
return insideDiameter;
}
// validates diameter and sets diameter
public void setInsideDiameter(double inDiameter)
{
insideDiameter = ((inDiameter >= MIN_DIAMETER &&
inDiameter <= MAX_DIAMETER) ? inDiameter : DEFAULT_DIAM_DEPTH);
}
// validates and sets last name
public void setLastName(String lastNameIn)
{
lastName = ((lastNameIn.length()) > 0 ? lastNameIn : DEFAULT_NAME);
}
// returns last name
public String getLastName()
{
return lastName;
}
// validates and sets first name
public void setFirstName(String firstNameIn)
{
firstName = ((firstNameIn.length()) > 0 ? firstNameIn : DEFAULT_NAME);
}
// returns first name
public String getFirstName()
{
return firstName;
}
// calculates total concrete necessary in cubic yards and returns that value
#Override
public double getConcreteVolume()
{
if(getInsideDiameter() == 0 || getInsideDepth() == 0)
return 0.000;
else
return (getCylinderVolume(getInsideDiameter() * FT_TO_IN + DENSITY +
DENSITY, getInsideDepth() + DENSITY) / CU_IN_TO_CU_YD) -
(getCylinderVolume(getInsideDiameter() * FT_TO_IN,
getInsideDepth())) / CU_IN_TO_CU_YD;
}
// private utility method used to calculate the volume of a cylinder
public double getCylinderVolume(double diameter, double height)
{
return (Math.PI * Math.pow(diameter / 2.0, 2)) * height;
}
} //end class Pool
Ever signed a contract before?
This code:
public class Pool implements BackYard
is just like one. It's like Pool saying to Backyard: "Hey Backyard, I'm signing a contract that guarantees I'll create code for all the methods you have."
But Pool violated the contract.
The police (compiler) finds out about it and says: Do it buddy or make your kids do it.
Either you fullfil the contract yourself (i.e. create code for all methods mentioned in Backyard) or let your descendants be the ones to complete it (the subclasses will be the ones to add code). You're kind of "punished" - keeping you in an abstract state until the commitment is completed.
First concrete class must implement all abstract methods from its supertypes. In your case you either make Pool abstract, all implement all abstract methods from supertypes that are not already implemented.
In other words, If you allowed not abstract class Pool to have abstract methods, then client of your library could do
Pool p = new Pool();
p.getBollardHeight();
which cannot work, because this method is not implemented. If, on the other hand, you made Pool abstract, you would not be allowed to instantiate it and the problem above would not occur.
You must create all the methods you see in BackYard, inside the Pool class

Categories

Resources