I'm trying to make this piece of code print the actual numbers, and not the hexadecimal location.
public class MoneyDriver
{
//This is a driver for testing the class
public static void main(String[] args)
{
final int BEGINNING = 500;
final Money FIRST_AMOUNT = new Money(10.02);
final Money SECOND_AMOUNT = new Money(10.02);
final Money THIRD_AMOUNT = new Money(10.88);
Money balance = new Money(BEGINNING);
System.out.println("The current amount is " +
balance.toString());
balance = balance.add(SECOND_AMOUNT);
System.out.println("Adding " + SECOND_AMOUNT +
" gives " + balance.toString());
balance = balance.subtract(THIRD_AMOUNT);
System.out.println("Subtracting " + THIRD_AMOUNT +
" gives " + balance.toString());
boolean equal = SECOND_AMOUNT.equals(FIRST_AMOUNT);
if(equal)
System.out.println(SECOND_AMOUNT + " equals "
+ FIRST_AMOUNT);
else
System.out.println(SECOND_AMOUNT.toString() +
" does not equal " + FIRST_AMOUNT);
equal = THIRD_AMOUNT.equals(FIRST_AMOUNT);
if(equal)
System.out.println(THIRD_AMOUNT + " equals " +
FIRST_AMOUNT);
else
System.out.println(THIRD_AMOUNT + " does not equal "
+ FIRST_AMOUNT);
}
}
This is the main class which is called by moneydriver
public class Money
{
private long dollars;
private long cents;
public Money(double amount)
{
if (amount < 0)
{
System.out.println(
"Error: Negative amounts of money are not allowed.");
System.exit(0);
}
else
{
long allCents = Math.round(amount*100);
dollars = allCents/100;
cents = allCents%100;
}
}
public Money add(Money otherAmount)
{
Money sum = new Money(0);
sum.cents = this.cents + otherAmount.cents;
long carryDollars = sum.cents/100;
sum.cents = sum.cents%100;
sum.dollars = this.dollars
+ otherAmount.dollars + carryDollars;
return sum;
}
public Money subtract (Money amount)
{
Money difference = new Money(0);
if (this.cents < amount.cents)
{
this.dollars = this.dollars - 1;
this.cents = this.cents + 100;
}
difference.dollars = this.dollars - amount.dollars;
difference.cents = this.cents - amount.cents;
return difference;
}
public int compareTo(Money amount)
{
int value;
if(this.dollars < amount.dollars)
{
value = -1;
}
else if (this.dollars > amount.dollars)
{
value = 1;
}
else if (this.cents < amount.cents)
{
value = -1;
}
else if (this.cents > amount.cents)
{
value = 1;
}
else
{
value = 0;
}
return value;
}
}
The objectives is to write equals method (on main class). The method compares the instance variables of the calling object with instance variables of the parameter object for equality and returns true if the dollars and the cents of the calling object are the same as the dollars and the cents of the parameter object. Otherwise, it returns false.
Write toString method (on main class). This method will return a String that
looks like money, including the dollar sign. Remember that if you have less than 10 cents, you will need to put a 0 before printing the cents so that it appears correctly with 2 decimal places.
If both of the method is implemented correctly
According to tutorialspoint, you're supposed to do either
String toString()
static String toString(int i)
But the supplied moneydriver already has the tostring method, but doesn't display the numbers, instead it displays a hexadecimal location of the variable.
The equals method is already used in moneydriver, so I'm kinda lost on that too.
The correct output should look like this
The current amount is $500.00
Adding $10.02 gives $510.02 Subtracting $10.88 gives $499.1
$10.02 equals $10.02
$10.88 does not equal $10.02
Completely lost in this, thanks in advance for help.
To get a String output on the Money class, do something akin to:
public class Money
{
private long dollars;
private long cents;
// suggested approach for constructor
public Money(long amount) throws IllegalArgumentException
{
if (amount < 0) {
throw new IllegalArgumentException("Amount may not be less than 0");
}
// do other stuff
}
...
public String toString()
{
return String.format("%d.%02d", dollars, cents);
}
public boolean equals(Object obj)
{
boolean equal = false;
if (obj instanceof Money) {
Money chk = (Money)obj;
equal = (chk.dollars == this.dollars &&
chk.cents == this.cents);
}
return equal;
}
} // end class Money
Related
I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.
public class PizzaEx {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char letter;
String input;
int sizeD;
int pizzaCount=1;
Pizza pieOne;
do{
sizeD = getValidSize();
input = JOptionPane.showInputDialog(null, "What type of topping do you wish to order? " +
"\n Green Pepper" +
"\n Mushroom"+
"\n Sausage"+
"\n Pepperoni"+
"\n Plain");
pieOne = new Pizza(sizeD, input);
System.out.println(pieOne);
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() +"."+"\n");
input = JOptionPane.showInputDialog(null, "Do you wish to continue?\n "+
"'y' or 'Y' for YES\n"+
"'n' or 'N' for NO\n");
letter = input.charAt(0);
pizzaCount = pizzaCount +1;
}
while (letter == 'Y'|| letter == 'y');
System.exit(0);
}
private static int getValidSize()
{
int d;
String input;
do{
input = JOptionPane.showInputDialog(null, "What size of pizza do you wish to order? "+
"\n 9 inch"+
"\n 12 inch"+
"\n 16 inch");
d = Integer.parseInt(input);
} while (!(d==9 || d==12 || d==16));
return d;
}
so the above is my main class
public class Pizza {
private int diameter;
private int numOfPizza;
private double price;
private String tops;
Pizza(int sizeD, String input) {
diameter = sizeD;
tops = input;
}
public int getDiameter(){
return diameter;
}
/**
*
* #param pizzaCount
* #return
*/
public int getPizzaCount(){
return numOfPizza;
}
public double getPrice(){
return price;
}
public String getToppings(){
return tops;
}
public void setDiameter(int sizeD){
if (sizeD == 9)
diameter = 9;
else if ( sizeD == 12)
diameter = 12;
else if (sizeD == 15)
diameter = 15;
else
diameter = 0;
}
public void setPizzaCount(int pizzaCount){
numOfPizza = pizzaCount;
}
public void setPrice(double total){
price = total;
}
public void setToppings(String input){
if ("green pepper".equalsIgnoreCase(input))
tops = "Green Pepper";
else if ("mushroom".equalsIgnoreCase(input))
tops = "Mushroom";
else if ("sausage".equalsIgnoreCase(input))
tops = "Sausage";
else if ("pepperoni".equalsIgnoreCase(input))
tops = "Pepperoni";
else
tops = "Plain";
}
private double calculatePrice(int sizeD, String input){
double total;
if (sizeD == 9 && (tops).equalsIgnoreCase("plain"))
total = 5.95;
else if (sizeD == 9)
total = 6.95;
else if (sizeD == 12 && (tops).equalsIgnoreCase("plain") )
total = 7.95;
else if (sizeD == 12)
total = 8.95;
else if (sizeD == 16 && (tops).equalsIgnoreCase("plain"))
total = 9.95;
else if (sizeD == 16)
total = 10.95;
else
total = 0.0;
return total;
}
public String toString(){
String pizzaString ="You have ordered a "+diameter + " inch pizza with "+tops +" toppings and a price of $"+ calculatePrice(diameter, tops);
return pizzaString;
}
When I do the the print out, it keeps saying amount of pizza made are = 0 even though I set pizzaCount = 1. Also when it ask for topping, if I type any String besides the valid topping choices {"green peppers", "mushroom", "sausage", "pepperoni", "plain"} it will count the String as a topping and will be charged for the topping when it should be anything that is not {"green peppers", "mushroom", "sausage", "pepperoni"} should be considered "plain"
This is not a homework assignment or test problem. It was some extra practice handed out by my professor and is not for a grade. I just want some help to clarify why the String tops is not being assigned the value that the method setToppings() is calling to do.
The reason why you always get 0 with getNumOfPizza() is because you never increment int numOfPizza, you only increment pizzaCount in main.
As for the topping, the reason why you charge for toppings even if you enter an invalid String, is because of your logic in calculatePrice, where you charge for topping if !equalsIgnoreCase("plain"). In other words, anything except for "plain" will be considered a topping. In fact, the logic in this method is unnecessarily convoluted, I suggest you simplify some of the if statements:
private double calculatePrice(int sizeD, String input){
if(!(tops).equalsIgnoreCase("plain")) {
total = 1;
} else {
total = 0;
}
if(sizeD == 9) {
total += 5.95;
}
else if(sizeD == 12) {
total += 7.95;
}
else if(sizeD == 16) {
total += 9.95;
}
return total;
}
Your class Pizza has a field private int numOfPizza; which you are accessing with pieOne.getPizzaCount(). Because that field hasn't been initialized (and it is a primitive int) it has a default value of 0. One possible fix,
private int numOfPizza = 1;
Be sure that you are considering which count you are interested in; the local count or the Pizza count. Once that is fixed, you should also change
pizzaCount = pizzaCount +1;
to something like
pizzaCount += pieOne.getPizzaCount();
You have the following constructor:
Pizza(int sizeD, String input) {
diameter = sizeD;
tops = input;
}
As you can see it does not run your logic from setToppings.
It also does not set numOfPizza and you do not call your setPizzaCount() method either. So this class variable remains 0
You seem to have two different fields to hold the number of pizzas. The pizza class should only hold data about the individual pizzas and the other class should hold the data about the amount of pizzas. In your main class you initialize pizzaCount to 1, but then try getting the number from the pizza numOfPizza field.
Edit Also, on a separate note, your main class has too much going on in there. You should abstract some stuff out and put it in methods.
When you print:
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() +"."+"\n");
you are accessing pieOne. Lets check initialization:
Pizza pieOne = new Pizza(sizeD, input);
where sizeD stores the pizza size (like 9) and input stores a String.
The function pieOne.getPizzaCount() checks inside pieOne and returns numOfPizza;
public int getPizzaCount(){
return numOfPizza;
}
But since you never actually stored that value inside the object, it will return zero!
You net to call setPizzaCount() before printing anything.
Hope it helps.
The reason the String for toppings is coming back as whatever the user types every time is because the setToppings() method is declared but never called. You need to call it on the "tops" variable for it to work. As it is, the program skips the method altogether.
Here is one way you could call the method in your program:
public String toString()
{
//method call
setToppings(tops);
String pizzaString = "You have ordered a " + diameter + " inch pizza with " + tops + " toppings and a price of $" + calculatePrice(diameter, tops);
return pizzaString;
}
}
The problem with your number of pizzas is the same situation. The setPizzaCount() method had never been called, therefore numOfPizza was never set. Since int variables automatically default to 0 if they are not instantiated, you get a value of 0 every time. Also, you may want to consider using the increment (++) operator when you add one to the number of pizzas. It exists to help make your code easier for you to write and for others to understand when incrementing numbers.
Here's an example:
do
{
sizeD = getValidSize();
input = JOptionPane.showInputDialog(null, "What type of topping do you wish to order? " +
"\n Green Pepper" +
"\n Mushroom" +
"\n Sausage" +
"\n Pepperoni" +
"\n Plain");
pieOne = new Pizza(sizeD, input);
//method call
pieOne.setPizzaCount(pizzaCount);
System.out.println(pieOne);
System.out.println("The Number of pizzas made are " + pieOne.getPizzaCount() + "." + "\n");
input = JOptionPane.showInputDialog(null, "Do you wish to continue?\n " +
"'y' or 'Y' for YES\n" +
"'n' or 'N' for NO\n");
letter = input.charAt(0);
pizzaCount++;
}
Hello I am trying to write a code that satisfies the following output:
Here are the booths at the start:
Ticket booth with 5 passes and 50 tickets
Ticket booth with 1 passes and 10 tickets
Booth 1 has made $43.0
Booth 2 has made $20.5
Here are the booths at the end:
Ticket booth with 3 passes and 30 tickets
Ticket booth with 0 passes and 2 tickets
I was able to do it for the first three lines but I am having trouble writing my methods for sellPass() ,sellTickets() and moneyMade() . Here is the following tester code that is supposed to output my code:
public class TicketBoothTestProgram
{
public static void main(String args[])
{
TicketBooth booth1, booth2;
booth1 = new TicketBooth(5, 50);
booth2 = new TicketBooth(1, 10);
System.out.println("Here are the booths at the start:");
System.out.println(" " + booth1);
System.out.println(" " + booth2);
// Simulate selling 2 passes, 5 tickets, 12 tickets and 3 tickets from booth1
booth1.sellPass();
booth1.sellPass();
booth1.sellTickets(5);
booth1.sellTickets(12);
booth1.sellTickets(3);
// Simulate selling 2 passes, 5 tickets, 12 tickets and 3 tickets from booth2
booth2.sellPass();
booth2.sellPass();
booth2.sellTickets(5);
booth2.sellTickets(12);
booth2.sellTickets(3);
// Make sure that it all worked
System.out.println("\nBooth 1 has made $" + booth1.moneyMade);
System.out.println("Booth 2 has made $" + booth2.moneyMade);
System.out.println("\nHere are the booths at the end:");
System.out.println(" " + booth1);
System.out.println(" " + booth2);
}
}
and here is the code in which I am trying to write my methods:
public class TicketBooth
{
float moneyMade;
int availablePasses;
int availableTickets;
static float TICKET_PRICE = 0.50f;
static float PASS_PRICE = 16.50f;
public TicketBooth()
{
moneyMade = 0.0f;
availablePasses = 0;
availableTickets = 0;
}
public TicketBooth(int p)
{
moneyMade = 0.0f;
availablePasses = p;
availableTickets = 0;
}
public TicketBooth(int p, int t)
{
moneyMade = 0.0f;
availablePasses = p;
availableTickets = t;
}
public String toString()
{
return("Ticket booth with " + this.availablePasses + " passes and " + this.availableTickets +
" tickets");
}
public sellPass()
{
//INSERT CODE HERE FOR SELLING A PASS
}
public sellTickets()
{
//INSERT CODE HERE FOR SELLING A TICKET
}
}
Any help is appreciated thank you!
Your sellPass() method is fairly simple. I have added boolean return types which will retun false if you run out of tickets or passes.
public boolean sellPass() {
//Check if you have a pass to sell
if (availablePasses > 0) {
//you have passes to sell
moneyMade += moneyPerPass; // add the money
availablePass--; //decrement pass counter
return true;
}
return false; // not enough passes to sell
}
Same way your sellTickets(int noOfTickets), your method should allow how many tickets you want to sell.
public boolean sellTickets(int noOfTickets) {
if(availableTickets >= noOfTickets) {
moneyMade += noOfTickets * pricePerTicket;
availableTickets -= noOfTickets;
return true;
}
return false;
}
So I've been looking at this piece of code all afternoon and I can't see the error(s). Here is what I'm supposed to do:
Create a Delivery class for a delivery service. The class contains fields to hold the following:
A delivery number that contains eight digits. The first four digits represent the year, and the last four digits represent the delivery number.
A code representing the delivery area. A local delivery is code 1, and a long distance delivery is code 2.
A weight, in pounds, of the item to be delivered.
The fee for the delivery, as follows:
Create a constructor for the Delivery class that accepts arguments for the year,
delivery number within the year, delivery distance code, and weight of the package. The
constructor determines the eight-digit delivery number and delivery fee. Also include a
method that displays every Delivery object field. Save the file as Delivery.java.
Next, create an application that prompts the user for data for a delivery. Keep
prompting the user for each of the following values until they are valid:
A four-digit year between 2001 and 2025 inclusive
A delivery number for the year between 1 and 9999 inclusive
A package weight between 0.10 pound and 100 pounds inclusive
A delivery distance code that is either 1 or 2
When all the data entries are valid, construct a Delivery object, and then display its
values. Save the file as CreateDelivery.java.
So here is my delivery Class
import javax.swing.*;
import java.util.*;
class Delivery
{
//variables
private int year;
private int deliveryNumber; //deliveryNo
private double weight;
private int distanceCode; //code
//constructor
//Delivery()
//{
// year = year;
// deliveryNumber = deliveryNumber;
// weight = weight;
// distanceCode = distanceCode;
//}
//get year
public int getYear()
{
return year;
}
//set year
public int setYear (int newYear)
{
year = newYear;
return year;
}
//get deliveryNumber
public int getDeliveryNumber()
{
return deliveryNumber;
}
//set deliveryNumber
public int setDeliveryNumber (int newDeliveryNumber)
{
deliveryNumber = newDeliveryNumber;
return deliveryNumber;
}
//get weight
public double getWeight()
{
return weight;
}
//set Weight
public double setWeight (double newWeight)
{
weight = newWeight;
return weight;
}
//get distanceCode
public int getDistanceCode()
{
return distanceCode;
}
//set distanceCode
public int setDistanceCode (int newDistanceCode)
{
distanceCode = newDistanceCode;
return distanceCode;
}
//calculate fee
public double displayFees(int distance, double w) //distance = c
{
double fees = 0;
if(distance == 1)
{
if(w < 5)
{
fees = 12;
}
else if((w < 20)&&(w > 5))
{
fees = 16.50;
}
else if(w > 20)
{
fees = 22;
}
}
else if(distance == 2)
{
if(w < 5)
{
fees = 35;
}
else if(w >= 5)
{
fees = 47.95;
}
}
return fees;
}
//display method
public void display(int year, int deliveryNumber, double weight, int distanceCode)
{
System.out.println("Year: " + year + '\n'
+ "Delivery Number: " + deliveryNumber + '\n'
+ "Weight of the package: " + weight + '\n'
+ "Delivery code: " + distanceCode);
}
}
And here is my CreateDelivery Class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class CreateDelivery
{
public static void main(String []args)
{
Delivery delivery1 = new Delivery();
//scanner year
Scanner input = new Scanner(System.in);
System.out.print("Please enter the current year, format (yyyy) >>> ");
delivery1.setYear(input.nextInt());
//loop year
while((delivery1.getYear() <= 2000)||(delivery1.getYear() >= 2026))
{
System.out.println('\n'+ "Error, year should be in the range of (2010 - 2025). Please enter a valid option >> ");
delivery1.setYear(input.nextInt());
}
//scanner for delivery number
System.out.print('\n'+ "Please enter a delivery number: ");
delivery1.setDeliveryNumber(input.nextInt());
//loop for delivery number
while((delivery1.getDeliveryNumber() <= 0001)||(delivery1.getDeliveryNumber() >= 10000))
{
System.out.println("Error, the delivery number is a 4 digit number between 0001 and 9999, please enter a valid option >> ");
delivery1.setDeliveryNumber(input.nextInt());
}
//scanner for weight
System.out.print("Please enter the weight of the package (in pounds): ");
delivery1.setWeight(input.nextDouble());
//loop for weight
while((delivery1.getWeight() <= .09)||(delivery1.getWeight() >= 101))
{
System.out.println("Error, the minimum allowed weight is 0.10 pounds and the maximum is 100 pounds. Please enter a valid weight >> ");
delivery1.setWeight(input.nextDouble());
}
//scanner for delivery code
System.out.print("Please enter 1 for local or 2 for long distance deliveries >> ");
delivery1.setDistanceCode(input.nextInt());
//loop for delivery code
while((delivery1.getDistanceCode() == 1) && (delivery1.getDistanceCode() == 2))
{
System.out.println("Error, please enter a valid distance code (1 for local deliveries and 2 for long distance deliveries) >> ");
delivery1.setDistanceCode(input.nextInt());
}
//turn int to string
String n = Integer.toString(delivery1.getDeliveryNumber());
String y = Integer.toString(delivery1.getYear());
String trackingNumber = n + y;
System.out.println(delivery1.getDistanceCode() + " "
+ trackingNumber + " " + delivery1.getWeight() + " " + fees);
}
}
So I made the changes you guys suggested, but now I can't pull fees from the Delivery class. Any thoughts?
Delivery()
{
year = year;
deliveryNumber = deliveryNumber;
weight = weight;
distanceCode = distanceCode;
}
Replace it with something along the lines of:
Delivery(int year, int deliveryNumber, int weight, int distanceCode)
{
this.year = year;
this.deliveryNumber = deliveryNumber;
this.weight = weight;
this.distanceCode = distanceCode;
}
From there, I would avoid using the set methods. Instead, store all the values into respective fields as you load them from the System.in. Once you have all the fields, create the Delivery object.
I think you are missing () at the end of the methods such as getDeliveryNumber,getYear etc. in the while loop.
and you are also using undeclared variables at the end such as getDeliveryNumber,getYear etc.
or we can do that simply like Delivery class
public class Delivery {
private int year,deliveryNumber,distanceCode;
private double weight;
private double fees=0;
//delivery class constructor
public Delivery(int year,int deliveryNumber,int distanceCode,double weight)
{
this.year=year;
this.deliveryNumber=deliveryNumber;
this.distanceCode=distanceCode;
this.weight=weight;
}
//calculate delivery fee
public void displayFees(int distanceCode, double weight)
{
if(distanceCode == 1)
{
if(weight<5)
{
fees = 12;
}
else if((weight < 20)&&(weight >=5))
{
fees = 16.50;
}
else if(weight > 20)
{
fees = 22;
}
}
else if(distanceCode == 2)
{
if(weight <5)
{
fees = 35;
}
else if(weight >= 5)
{
fees = 47.95;
}
}
}
public double getFee()
{
return fees;
}
}
and CreateDelivery class:
public class CreateDelivery {
public static void main(String[] args) {
int year=(int)ReadValues.readValue("Year", 1999,2026);
int deliveryNumber=(int)ReadValues.readValue("Delivery Number (1 to 10000)", 0,10000);
int distanceCode=(int)ReadValues.readValue("DistanceCode (1 or 2)",0, 3);
double weight=ReadValues.readValue("weight",0, 20);
Delivery delivery=new Delivery(year, deliveryNumber, distanceCode, weight);
delivery.displayFees(distanceCode, weight);
double fee=delivery.getFee();
System.out.println("\n\n*****Delivery Fees Details*****\n\nTrackingNumber:"+year+deliveryNumber+"\nDistanceCode:"+distanceCode+"\nFee :"+fee);
}
}
and for reading values from user another class called ReadValue
import java.util.Scanner;
public class ReadValues {
public static double readValue(String prompt, int min, int max) {
Scanner scan = new Scanner(System.in);
double value;
System.out.print(prompt + " :");
while (true) {
value = scan.nextDouble();
if (value < min || value > max)
System.out.println("Enter value between " + min + " & " + max);
else
break;
}
return value;
}
}
I'm having a hard time wrapping my head around object based programming. Im attempting to invoke a method from a class. However, all I invoke is a variable that has been declared, while I'm trying to pull the variable later. (Im sure my terminology is off - feel free to correct)
Im getting logic errors. Instead of a value, im getting "null".
The Class:
public class NumberOperations {
int number;
String oddsUnder;
String powersTwoUnder;
int isGreater;
String toString;
public NumberOperations(int numberIn) {
number = numberIn;
}
public int getValue() {
return number;
}
public String oddsUnder() {
String output = "";
int i = 0;
while (i < number) {
if (i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder() {
String output2 = "";
int powers = 1;
while (powers < number) {
output2 += powers + "\t";
powers = powers * 2;
}
return output2;
}
public int isGreater(int compareNumber) {
if (number > compareNumber) {
return 1;
}
else if (number < compareNumber) {
return -1;
}
else {
return 0;
}
}
public String toString() {
return number + "";
}
}
The Program:
import java.util.Scanner; import java.util.ArrayList;
/** * Demonstrates the NumberOperations class. */ public class NumberOpsDriver {
/**
* Reads a set of positive numbers from the user until the user enters 0. * Prints odds under and powers of 2 under for each number. *
* #param args - Standard commandline arguments
*/ public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int firstInput = in.nextInt();
// add a while loop as described below:
while (firstInput != 0) {
numOpsList.add(new NumberOperations(firstInput));
firstInput = in.nextInt();
}
// while the input is not "0"
// add NumberOperations object to array based on user input
// get the next user input using in.nextInt()
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
System.out.println("Odds under: " + num.oddsUnder);
System.out.println("Powers of 2 under: " + num.powersTwoUnder);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
} } }
You never assign to your member variables oddsUnder and powersTwoUnder. So of course they are null when you read them, and when you try to print them you have a NullPointerException it prints "null".
You probably actually want to call the methods of the same name instead of taking the variables
System.out.println("Odds under: " + num.oddsUnder());
System.out.println("Powers of 2 under: " + num.powersTwoUnder());
Make your properties as private to avoid this kind of situations and change your properties in System.out... to call the methods not the object fields. For example
System.out.println("Odds under: " + num.oddsUnder()); //<-changed