Trouble with displaying info from getter method - java

QUESTION: I'm trying to find the win percentage (the formula for win percentage is wins/(wins + loses)). How do I take the values from wins and loses the user enters and add them to my Sysout function. Every time I run the program it displays:
East W L PCT
Braves 45 66 0.000000
Cubs 87 77 0.000000
So what I'm trying to do is get the actual values instead of it saying "0.0000000"
public class Team {
// Data fields...
private int wins;
private int loses;
private String teamName;
private String city;
private String division;
private double winPercentage;
// Getters and setters...
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getLoses() {
return loses;
}
public void setLoses(int loses) {
this.loses = loses;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public double getWinPercentage() {
return wins/(wins + loses);
}
public void setWinPercentage(double winPercentage) {
this.winPercentage = winPercentage;
}
}
public class PlayoffSelectorClass extends Team{
public static void main(String[] args) {
List<Team> teams = new ArrayList<Team>();
for (int i = 0; i < 6; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter team name: ");
String name = input.nextLine();
System.out.println("\nPlease enter the city " + name + " played in: ");
String city = input.nextLine();
System.out.println("\nPlease enter the division " + name + " play in: ");
String division = input.nextLine();
System.out.println("\nPlease enter the number of wins " + name + " has: ");
Integer wins = input.nextInt();
System.out.println("\nPlease enter the number of losses " + name + " has: ");
Integer loses = input.nextInt();
if (i < 5) {
System.out.println("\nEnter your next team...\n");
}
Team team = new Team();
team.setTeamName(name);
team.setCity(city);
team.setDivision(division);
team.setWins(wins);
team.setLoses(loses);
team.setWinPercentage(wins / (wins + loses));
teams.add(team);
}
System.out.println("East W L PCT\n");
for (Team team : teams) {
System.out.printf("%s\t%s\t%s\t%f\n",team.getTeamName() + " ", team.getWins() + " " , team.getLoses(), team.getWinPercentage());
}
}
}

The problem is here :
public double getWinPercentage() {
return wins/(wins + loses);
}
You are doing integer division, i.e only keep the int part of the result, and implicitly cast it to a double. So for example if:
wins = 10;
loses = 20;
then winPercentage == 10/30 == 0.33.. and you only keep the 0 and the cast it to double. Hence the 0.0000... etc What you can do instead is:
public double getWinPercentage() {
return wins/(double) (wins + loses);
}

Related

Trouble getting input for object array

I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:
APExam:
public class APExam {
//instance variables
private String mySubject;
private int myScore;
//constructors
public APExam(String subject, int score) {
mySubject = subject;
myScore = score;
}
public APExam() {
mySubject = "";
myScore = 1;
}
//getters and setters
public void setSubject(String s) {
mySubject = s;
}
public String getSubject() {
return mySubject;
}
public void setScore(int score) {
myScore = score;
}
public int getScore() {
return myScore;
}
//compareTo
public String compareTo(int s) {
if(myScore == s)
return "Scores are equal.";
else if(myScore > s)
return "The first score is greater than the second score.";
else
return "The second score is greater than the first score.";
}
//equals
public boolean equals(String str) {
return mySubject.equals(str);
}
//toString
public String toString() {
return "Subject: " + mySubject + "\nScore: " + myScore;
}
}
APStudent:
public class APStudent {
//instance variables
private String myFirstName;
private String myLastName;
private ArrayList<APExam> myExams = new ArrayList<APExam>();
//constructors
public APStudent(String fname, String lname) {
myFirstName = fname;
myLastName = lname;
}
public APStudent() {
myFirstName = "";
myLastName = "";
}
//getters and setters
public void setFirstName(String fname) {
myFirstName = fname;
}
public String getFirstName() {
return myFirstName;
}
public void setLastName(String lname) {
myLastName = lname;
}
public String getLastName() {
return myLastName;
}
public ArrayList<APExam> getExams() {
return myExams;
}
//addExam
public void addExam(APExam ex) {
myExams.add(ex);
}
//computeExamAverage
public double computeExamAverage(List<APExam> exams) {
int sum = 0;
for(int i = 0; i < exams.size(); i++) {
sum += exams.get(i).getScore();
}
return (double) sum / exams.size();
}
//findHighestExamScore
public int findHighestExamScore(List<APExam> exams) {
int max = exams.get(0).getScore();
for(APExam ex : exams) {
if(ex.getScore() > max) {
max = ex.getScore();
}
}
return max;
}
//numberOfFives
public int numberOfFives(List<APExam> exams) {
int fiveCount = 0;
for(APExam ex : exams) {
if(ex.getScore() == 5) {
fiveCount++;
}
}
return fiveCount;
}
}
ArrayListTest:
public class ArrayListTest {
public static void main(String[] args) {
//instance variables
final String QUIT = "end";
Scanner sc = new Scanner(System.in);
ArrayList<APExam> myExams = new ArrayList<APExam>();
APStudent student = new APStudent();
String fname, lname, sub, input = "";
int score;
//prompt for info
System.out.print("Enter first name: ");
fname = sc.nextLine();
student.setFirstName(fname);
System.out.print("\nEnter last name: ");
lname = sc.nextLine();
student.setLastName(lname);
while(!input.equals(QUIT)) {
APExam ap = new APExam();
System.out.print("\nEnter exam subject or 'end' to quit: ");
input = sc.nextLine();
sub = input;
ap.setSubject(sub);
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
ap.setScore(score);
student.addExam(ap);
sc.nextLine();
}
//display information
System.out.println(student.getExams());
System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
System.out.println("Exam average score: " + student.computeExamAverage(myExams));
System.out.println("Highest score: " + student.findHighestExamScore(myExams));
System.out.println("Number of fives: " + student.numberOfFives(myExams));
System.out.println();
for(int i = 0; i < myExams.size(); i++) {
System.out.println(myExams.get(i));
}
//prompt for search
System.out.println("1 sequential search"
+ "\n2 binary search"
+ "\n3 exit");
input = sc.nextLine();
while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
switch(input) {
case "1":
sequentialSearch(myExams, 3);
break;
case "2":
binarySearch(myExams, 2);
break;
case "3":
break;
}
}
}
}
For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?
Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.
You shouldn't pass anything and just use the APStudent's myExams list.
public double computeExamAverage() {
double sum = 0;
for (APExam myExam : myExams) {
sum += myExam.getScore();
}
return sum / myExams.size();
}
public int findHighestExamScore() {
int max = 0;
for(APExam exam : myExams) {
if(exam.getScore() > max) max = exam.getScore();
}
return max;
}
public int numberOfFives() {
return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}
EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.
public static void main(String[] args) {
final String QUIT = "end"; // not really necessary, but ok
Scanner sc = new Scanner(System.in);
String firstName, lastName, subject;
int score;
//prompt for info
System.out.print("Enter first name: ");
firstName = sc.nextLine();
System.out.print("\nEnter last name: ");
lastName = sc.nextLine();
APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
while(true) {
System.out.print("\nEnter exam subject or 'end' to quit: ");
subject = sc.nextLine();
if (subject.equals(QUIT)) break; // check if user wants to end it
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
student.addExam(new APExam(subject, score)); // use of parametrized constructor
sc.nextLine();
}
sc.close(); // never forget to close Scanner
//display information etc.
}

I have some issue with my output

The Cullerton Part District holds a mini-Olympics each summer. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values. Also include an equals() method that determines two Participants are equal if they have the same values in all three fields. Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as BC.java and ABC.java.
import javax.swing.JOptionPane;
import java.util.*;
public class ABC {
private static Participant mini[] = new Participant[2];
public static void main(String[] args) {
setParticipant();
displayDetail();
}
// BC p=new BC(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
}
}
}
//another class
public class BC {
private String name;
private int age;
private String address;
public BC(String strName, int intAge, String strAddress) {
name = strName;
age = intAge;
address = strAddress;
}
#Override
public String toString() {
return "Participant [name=" + name + ", age=" + age + ", address=" + address + "]";
}
public boolean equals(Participant value){
boolean result;
if (name.equals(name) && age==value.age && address.equals(address))
result=true;
else
result=false;
return result;
}
}
outPut:
Enter loan details for customer 1...
Participant name: hddgg
Enter Address: 122
Enter age 12
Enter loan details for customer 2...
Participant name: ddjkjde
Enter Address: hdhhd23
Enter age 12
//Why I'm not getting right output
Name Adress Age
Participant [name=null, age=0, address=null]
Participant [name=null, age=0, address=null]
You are getting that output because of this method:
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
You are creating a BC with null for name and add and 0 for age. You are then printing it twice.

I'm trying to do stuff with inheritance but none of it will work

Im trying to get different variables from loan but none of them ever get to loan.java. My inheritance goes from Loan.Java > BusinessLoan.java > CreateLoan.java. I can get a variable from CreateLoan to display in business but when I set it in business I can't grab it. And I know some of this stuff is stupid but this is my final so some of the stuff was required. Heres my code
Loan.java
package Construction;
public class Loan implements LoanConstant{
public static int loanNumber;
public static String lastName;
public static int loanAmount;
public static int interestRate;
public static int term;
public int primeRate;
public int getLoanNumber() { return loanNumber; }
public void setLoanNumber(int n) { n = loanNumber; }
public String getLastName() { return lastName; }
public void setLastName(String s) { s = lastName; }
public int getLoanAmount() { return loanAmount; }
public void setLoanAmount(int n) {
n = loanAmount;
if (loanAmount > MAX_LOAN_AMOUNT)
loanAmount = MAX_LOAN_AMOUNT;
}
public int getTerm() { return term; }
public void setTerm(int n) {
n = term;
if (term == 1) {
term = SHORT_TERM;
} else if (term == 3) {
term = MEDIUM_TERM;
} else if(term == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public int getInterestRate() { return interestRate; }
public void setInterestRate(int i) { i = interestRate; }
public static void displayAll() {
System.out.println("The Company's Name is " + COMPANY_NAME);
System.out.println("The loan number is " + loanNumber);
System.out.println("The last name on the loan is " + lastName);
System.out.println("The loan amount is " + loanAmount);
System.out.println("The interest rate on the loan is " + interestRate);
System.out.println("The term on the account is " + term);
}
}
PersonalLoan.java
package Construction;
public class PersonalLoan extends Loan{
public PersonalLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.02) + primeRate);
setInterestRate(interestRate);
}
}
BusinessLoan.java
package Construction;
public class BusinessLoan extends Loan{
public BusinessLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.01) + primeRate);
setInterestRate(interestRate);
}
}
CreateLoan.java
package Construction;
import java.util.Scanner;
public class CreateLoan {
public static void main(String[] args) {
int x = 0;
int primeRate;
String type;
Scanner input = new Scanner(System.in);
Loan[] loans = new Loan[5];
System.out.println("Please enter the prime interest rate");
primeRate = input.nextInt();
primeRate = primeRate/100;
input.nextLine();
for(x = 0; x < 6; ++x) {
System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
type = input.nextLine();
if (type.equalsIgnoreCase("Business")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new BusinessLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
}
else if (type.equalsIgnoreCase("Personal")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new PersonalLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
} else {
System.out.println("You've entered an invalid type. Please restart and try again.");
System.exit(0);
}
}
}
}
LoanConstants.java
package Construction;
public interface LoanConstant {
public final static int SHORT_TERM = 1;
public final static int MEDIUM_TERM = 3;
public final static int LONG_TERM = 5;
public final static String COMPANY_NAME = "Sanchez Construction";
public final static int MAX_LOAN_AMOUNT = 100000;
}
In addition to the Loan fields being static (remove the static). You should also update your setters.
public void setLoanNumber(int n) { n = loanNumber; }
public void setLastName(String s) { s = lastName; }
You are assigning the value to the passed in variable (not the field). Should be
public void setLoanNumber(int n) { loanNumber = n; }
public void setLastName(String s) { lastName = s; }
and
public void setTerm(int n) {
// n = term;
if (n == 1) {
term = SHORT_TERM;
} else if (n == 3) {
term = MEDIUM_TERM;
} else if (n == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public void setInterestRate(int i) { interestRate = i; }

Can't get this to compile, what am I doing wrong?

OK so I can see the "setUniqueType" on line 33 and the "ItemDetails" on line 50 are what need to be corrected, but I can't figure out what's wrong with it and how to fix it. Please help so I can move in with my program...
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
theItem.setUniqueType(Type);
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber, Type);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name" + inv[i].getName());
JOptionPane.showMessageDialog(null, "Product Type" + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number" + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock" + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit" + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem;
JOptionPane.showMessageDialog(null, combinedData);
}else{
JOptionPane.showMessageDialog(null, combinedData);
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public String enterUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
Compile errors:
RunApp.java:31: cannot find symbol
symbol : method setUniqueType(java.lang.String)
location: class ItemDetails
theItem.setUniqueType(Type);
^
RunApp.java:48: cannot find symbol
symbol : constructor ItemDetails(java.lang.String,double,double,double,java.lan
g.String)
location: class ItemDetails
inv[count] = new ItemDetails(Name, Price, Units, pNumber, Type);
^
2 errors
Your ItemDetails class has no setUniqueType method. You should add one.
The constructor you're using at :48 is "String, double, double, double, String" but your constructor is really only "String double double double" Either remove Type or add a String parameter to the end of your Item constructor, or make an ItemDEtails constructor with the five parameters.
Your ItemDetails has no constructor that matches that argument. If you want to chain the constructor, declare it in ItemDetails
Chaining the constructor:
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice
super(productName,productNumber,unitsInStock,unitPrice);
}
Regarding ItemDetails: it looks like your ItemDetails constructor, inherited from Items, takes only 4 args and you're passing it 5.

Why is my data mixed up when I compile?

There are a few things I would like some help on. First and foremost, when I compile, my product number and price get mixed up. Why? Secondly, why does the product type always return null? I would also like to combine all the message boxes but every attempt I have made fails. If someone could lead me in the right direction, I would appreciate it. Here is my code:
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays; //Needed to include data for arrays
import javax.swing.JOptionPane; //JOptionPane import tool
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name: " + inv[i].getName());
//Why can't I use this instead of having multiple boxes?:
//JOptionPane.showMessageDialog(null, "Product Name: \nProduct Type: \nProduct Number: \nUnits in Stock: \nPrice Per Unit: " + inv[i].getName() + inv[i].getUniqueType() + inv[i].getpNumber() + inv[i].getUnits(), + inv[i].getPrice());
JOptionPane.showMessageDialog(null, "Product Type: " + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number: " + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock: " + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit: " + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem; //combine total value to the end of the last object output
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}else{
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item) //This is used to set up the method
{
double combined = 0; //Loops through array after array is complete
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice(); //Sets up to combine all TotalPrice
//calculations in array
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
{
super(productName,productNumber,unitsInStock,unitPrice);
}
public String enterUniqueType()
{
return UniqueType;
}
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
// getter???
public String setUniqueType() {
return UniqueType;
}
should be:
//setter
public void setUniqueType(String type) {
UniqueType = type;
}
and
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
should be:
inv[count] = new ItemDetails(Name, pNumber, Units,Price );//look at the order
inv[count].setUniqueType(Type);//you have not set it.
I would also like to combine all the message boxes…
As an example, see JOptionPaneTest.
First and foremost, when I compile, my product number and price get mixed up. Why?
You're creating a new ItemDetails object with the call to
new ItemDetails(Name, Price, Units, pNumber);
but your constructor for ItemDetails is
ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
i.e., it takes the product number first and price last, not the other way around
Secondly, why does the product type always return null?
You're never actually setting your type, both your set and get methods do the same thing! That the setter is returning a value should've been a warning!
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
This is what it should be
public void setUniqueType(String type)
{
this.UniqueType = type;
}

Categories

Resources