package homeWork;
public class ShoppingBag {
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate){
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
// Transformer
public void place(int numItems, float theCost){
items = items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems(){
return items;
}
public float getRetailCost(){
return totalRetailCost;
}
public float getTotalCost(){
return totalRetailCost + (1 + taxRate);
}
public String toString(){
String result = "The bag contains " + items + " items";
result += "The retail cost of items is" + totalRetailCost;
result += "The total cost = " + getTotalCost();
return result;
}
}
package homeWork;
import java.util.*;
public class MainClass {
public static void main(String[] args){
Scanner conIn = new Scanner(System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
while(count != 0){
System.out.print("Enter cost: ");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
}
}
}
I have tried all that I have found on here to return result after completion of input. Ive done what my book has shown me to do but I am not getting a result. Just a nudge in the right direction would be helpful.
You are no printing the object anywhere. Print the object
System.out.print(sb);
Related
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...
can anyone help me with this.
the assignment is to use JOptionPane in arrays. the user will input the length of the array. then at the end of the program, it will display the largest number.
here is what i got so far:
import javax.swing.JOptionPane;
public class array
{
public static void main(String[] args)
{
String L;
int lenght;
L=JOptionPane.showInputDialog(null,"enter lenght: ");
lenght=Integer.parseInt(L);
int[]num = new int[lenght];
for(int counter = 0; counter < lenght ;counter++)
{
JOptionPane.showInputDialog(null,"enter #: "+(counter+0));
int max=num[0];
if (num[counter] > max)
{
max = num[counter];
}
}
JOptionPane.showMessageDialog(null,"the largest number is: " + max);
}
}
then there is this error:
error: cannot find symbol
maxis defined in scope of for loop. So it is not available outside of for.
Define it outside of the for loop and it should work:
public static void main(String[] args) {
String L;
int lenght;
L = JOptionPane.showInputDialog(null, "enter lenght: ");
lenght = Integer.parseInt(L);
int[] num = new int[lenght];
int max=0;
for (int counter = 0; counter < lenght; counter++) {
JOptionPane.showInputDialog(null, "enter #: " + (counter + 0));
max = num[0];
if (num[counter] > max) {
max = num[counter];
}
}
JOptionPane.showMessageDialog(null, "the largest number is: " + max);
}
Update:
You never store the input value to num[counter]
num[counter] = Integer.parseInt(JOptionPane.showInputDialog(null, "enter #: " + (counter + 0)));
package retedunits;
import java.util.Scanner;
public class RentedUnits {
private Integer TOTAL_NUMBER_RENT_UNITS; //Total number of rented units
private Double rentPerUnit; //Rent Per Unit
private Double maintainancePerUnit; //Average Maintainance cost per unit
private Integer currentUnitsRented; //Number of units currently occupied
private Double rentIncreaseFactor; //The level at which people leave
//PROFIT MAX
private Double maxRentForProfit;
private Integer maxUnitsForProfit;
public RentedUnits(Integer totalUnits, Double initalRentPerUnit, Double initialMaintainanceCost, Integer currentRented, Double rentIncreaseFactor){
this.TOTAL_NUMBER_RENT_UNITS = totalUnits;
this.rentPerUnit = initalRentPerUnit;
this.maintainancePerUnit = initialMaintainanceCost;
this.currentUnitsRented = currentRented;
this.rentIncreaseFactor = rentIncreaseFactor;
}
public Double getMaxRentForProfit() {
return maxRentForProfit;
}
public Integer getMaxUnitsForProfit() {
return maxUnitsForProfit;
}
private void increaseRent(Double increasedRent){
//For each $40 increase in rent one unit is vacant.
if(increasedRent > this.rentIncreaseFactor) {
//The number of units that will become vacant is one for every increase of rentIncreaseFactor
int numberVacate = (int) (increasedRent % this.rentIncreaseFactor);
this.currentUnitsRented -= numberVacate;
this.rentPerUnit += increasedRent;
}
else {
this.rentPerUnit += increasedRent;
}
}
private Double calculateProfit(){
//Calculate total rent collected from units that are rented
Double totalRent = this.currentUnitsRented * this.rentPerUnit;
//calculate the maintainanec of all units
Double totalMaintainence = this.TOTAL_NUMBER_RENT_UNITS * this.maintainancePerUnit;
return totalRent - totalMaintainence;
}
public void maximizeProfit(){
/*Keep increasing rent, and let people leave till the total collected
* rent keeps increasing.
*/
/* Assume you begin at all units occupied*/
Double maximumProfit = 0.0;
Double maxProfitRent = 0.0;
Integer maxProfitUnits = 0;
/* Keep increasing rent till all people leave while tracking max profit*/
while(this.currentUnitsRented == 0){
increaseRent(this.rentIncreaseFactor);
if(this.calculateProfit() > maximumProfit){
maximumProfit = this.calculateProfit();
maxProfitRent = this.rentPerUnit;
maxProfitUnits = this.currentUnitsRented;
}
}
this.maxRentForProfit= maxProfitRent;
this.maxUnitsForProfit = maxProfitUnits;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
RentedUnits rentedUnits = new RentedUnits(50, 600.0, 27.0, 50, 40.0);
rentedUnits.maximizeProfit();
System.out.println(rentedUnits.getMaxUnitsForProfit() + " units needs to be rented at " + rentedUnits.getMaxRentForProfit() + " rent per unit to get maximum profit.");
}
}
I was having some trouble with a program where I am suppose to allow a user to enter any amount of numbers into a program until they do not want to anymore. The program then should calculate the average and maximum of the numbers inputed. Where did I go wrong?
import java.util.Scanner;
public class DataSet
{
//Instance Variables
private double newValue;
private double sum;
private int count;
Scanner scan = new Scanner(System.in);
//Constructors
public DataSet()
{
double newValue = 0;
double sum = 0;
int count = 0;
}
public void run()
{
}
public double getaddValueToSet()
{
System.out.println("Please enter a number");
newValue = scan.nextDouble();
count += 1;
return newValue;
}
public double getSum()
{
sum += newValue;
return sum;
}
public double getAverage()
{
double average;
average = sum/count;
return average;
}
public double getMaximum()
{
double max=newValue;
if(newValue >= max)
{
max = newValue;
}
return max;
}
public String toString()
{
String str;
str = "Average: " + getAverage() + "\n" +
"Maximum: " + getMaximum();
return str;
}
}
import java.util.Scanner;
public class DataSetRunner
{
public static void main(String [] args)
{
String answer = "yes";
Scanner scan = new Scanner(System.in);
{
System.out.println("Do you want to enter another number?");
answer = scan.next();
}
while(answer.equals("yes"))
{
DataSet d1 = new DataSet();
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
}
}
}
DataSet d1 = new DataSet();
do {
System.out.println("Do you want to enter another number?");
answer = scan.next();
if (answer.equalsIgnoreCase("YES")) {
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
} else {
break;
}
} while (true);
I'm attempting to call a method in order to calculate average (calcavgnow).. I'm trying to have it calculate the average of all the numbers in the array and return the average to the caller. I'm hoping it can deal with any size array. I tried attempting below.. can anyone help me figure out what I am doing wrong?
import javax.swing.JOptionPane;
public class sdasfs {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
calcavgnow = total / SelectNumber;
}
JOptionPane.showMessageDialog(null, getTotal(numbers) + " divided by " + Numbers.length + " is " + getAvg(Numbers));
}
//Create method in order to calculate calcavgnow
public static double getAvg(int numbers[]){
return (double)getTotal(numbers)/numbers.length;
}
public static int getTotal(int numbers[]){
int total = 0;
for(int i:numbers)
total +=i;
return total;
}
}// end class
Have a separate method to calculate average. Don't do everything inside the same method. Learn to modularize your code. So others can easily get adopt to your code.
public static double getAvg(double numbers[]){
return getTotal(numbers)/numbers.length;
}
public static double getTotal(double numbers[]){
double total = 0;
for(double i:numbers)
total +=i;
return total;
}
import javax.swing.JOptionPane;
public class AvgCalculator {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
}
calcavgnow = total / SelectNumber;
JOptionPane.showMessageDialog(null, "The average entered is " + calcavgnow);
}
}