I cannot find out where my mathematical error is. I just cannot see why I continue to receive no values back for my determineCableSrvs method.
private static Scanner input = new Scanner(System.in); //STORES CUSTOMER NAME STRING VALUE
public static void main(String[] args)
{//BEGIN main()
//Variables
int subscription = 0; //STORES SUBSCRIPTION INTEGER VALUE
int moviesOnDemand = 0; //STORES MOVIES ON DEMAND INTEGER VALUE
double cableSrvs = 0; //STORES TOTAL CABLE SERVICE DECIMAL VALUE
double totalMovieCharges = 0; //STORES TOTAL MOVIE CHARGES DECIMAL VALUE
double total = 0; //STORES TOTAL DECIMAL VALUE
char confirm = 'Y'; //LOOP CONTROL VARIABLE SET TO Y
Calendar dateTime = Calendar.getInstance(); //STORES THE DATE VALUE
String customerName = "";
while(Character.toUpperCase(confirm) == 'Y') //START OF WHILE LOOP AUTOMATICALLY ENTERS
{
String customer = setCustNm(customerName);
double cable = setCablePkg(subscription);
double type = determineCableSrv(subscription, cableSrvs);
int movies = setMoviePurchase(moviesOnDemand);
totalMovieCharges = movies * 7; //CALCULATING THE TOTAL MOVIE ON DEMAND CHARGE
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
input.nextLine();
askNewSubscription(confirm);
printThankYou(confirm);
}
}
public static String setCustNm(String customerName)
{
// 1st prompt
System.out.printf("%n%n%nWELCOME TO SA CABLE %n");
System.out.printf("%nPlease enter your name: "); //PROMPTING USER TO ENTER NAME
customerName = input.nextLine(); //CAPTURES USERS NAME
return customerName;
}
public static int setCablePkg(int subscription)
{
do{
// 2nd Prompt DISPLAYING THE DIFFERENT PACKAGES AVAILABLE FOR SUBSCRIPTION
System.out.printf("%nSA CABLE - SUBSCRIPTION PACKAGES " +
"%n%n1. Basic: Local & major TV network channels %s" +
"%n2. Deluxe: Local, major TV, cable & 100 other channels %s" +
"%n3. Premium: Deluxe package plus HEB, on-demand & 300 other channels %s",
"$35.00", "75.00", "110.00") ;
System.out.printf("%n%nSelect your cable subscription package: ");
subscription = input.nextInt();//CAPTURING USER INPUT
}while (subscription < 1 || subscription > 3);
return subscription;
}
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
public static int setMoviePurchase(int moviesOnDemand)
{
System.out.printf("%nSA CABLE - MOVIES " +
"%n%nEnter the number of Movies-On-Demand-HD purchases: ");
moviesOnDemand = input.nextInt();
return moviesOnDemand;
}
public static char askNewSubscription(char confirm)
{
System.out.printf("\nEnter 'Y' to continue with a new subscription or 'N' to exit: ");
confirm = input.nextLine().charAt(0);
return confirm;
}
public static char printThankYou(char confirm)
{
if(Character.toUpperCase(confirm) == 'Y')
{
confirm = 'Y';
}
if (Character.toUpperCase(confirm) != 'Y')
{
confirm = 'N';
System.out.printf("Thank you for being a valued SA Cable customer!");
System.exit(0);
}
return confirm;
}
I'm having trouble with this part:
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
Here is how I'm calling the method:
double type = determineCableSrv(subscription, cableSrvs);
I cannot seem to get the return value. I need the value for:
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
and this print out statement:
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
You set subscription equal to 0 and never change it before passing it in to the determineCableSrv method. You do the same with cableSrvs, so the return value from your method is going to be 0. The cableSrvs variable isn't read inside the method, so it probably shouldn't be in input parameter to begin with.
Related
So I'm trying to write a program that stimulates the rise and fall of the Stock market 5 times.The user inputs a value to create a new Stock Market Object then with the value from the user, the stock market either is a bust(decrease) or a boom( increase). The issue I'm having is passing the value to each if statement with the change within the loop.When I run the program, It uses the same value I entered instead of using the value that was created after calling boom or bust. I'm thinking I should create a value outside the loop that holds it but I'm not sure how to do that with the user input.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Starting Market Value:");
double mv = in.nextDouble();
StockMarket u = new StockMarket(mv);
for (int i = 0; i < 5; i++) {
System.out.println("Boom (1) or Bust(2)? ");
int t = in.nextInt();
if (t == 1) {
System.out.println("Enter a percentage of increase as a decimal ( eg .5 ):");
double r = in.nextDouble();
if (t == 1) {
double e = u.boom(r);
System.out.println("The Stock Market is now at: " + e);
}
} else if (t == 2) {
System.out.println("Enter number of points lost:");
double l = in.nextDouble();
if (t == 2) {
double f = u.bust(l);
System.out.println("The Stock Market is now at: " + f);
}
}
}
}
}
Below is the class
public class StockMarket {
//Instance Variable Points
private double Points;
// Default no Argument Constructor
public StockMarket(){
this(0.0);
}
// Constructor #2
public StockMarket(double Points){
this.Points = Points;
}
//
public double getPoint(){
return Points;
}
public double boom(double x){
x = Points * (1 + x);
return x;
}
public double bust( double h){
h = Points - h;
return h;
}
}
Not actually sure what's wrong, just that at line 81 my scan object is skipped and then the program continues with no clear attempt to read anything, thoughts on what's wrong? btw working in eclipse
import java.util.*;
public class Hospital
{
//--- Instance Variables
private Patient patient;
private Scanner scan;
private double totalPrivateRoomCharges;
private double totalSemiPrivateRoomCharges;
private double totalWardRoomCharges;
private double totalTelephoneCharges;
private double totalTelevisionCharges;
private double totalReceipts;
//--- Constructors
public Hospital()
{
scan = new Scanner(System.in);
totalPrivateRoomCharges = 0;
totalSemiPrivateRoomCharges = 0;
totalWardRoomCharges = 0;
totalTelephoneCharges = 0;
totalTelevisionCharges = 0;
totalReceipts = 0;
mainMenu();
}
//--- Methods
public void mainMenu()
{
int ans = 0;
do
{
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Main Menu");
System.out.println();
System.out.println("1) Enter Patient Billing Information");
System.out.println("2) Print Daily Summary Report");
System.out.println("3) Exit");
System.out.println();
System.out.print("Selection: ");
ans = scan.nextInt();
System.out.println();
if(ans == 1)
{
patientBillingInfo();
}
if(ans == 2)
{
printSummaryReport();
}
}
while(ans != 3);
}
// precondition: none
// postcondition: displays a menu that allows the user to enter a patient's
// billing info which includes the patient's name, the number of days the
// patient stayed in the hospital, and the type of room
// (private, semi-private, ward).
// Once the patient info is retrieved a patient object is created and a
// billing report is generated that includes the patient's name, length
// of stay, and the charges incurred including the bill total.
// The totals that are used to print the hospitals daily summary report
// are updated.
public void patientBillingInfo()
{
String name = "";
int days = 0;
String room = "";
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Query");
System.out.println();
System.out.println("Enter Patient Name: ");
here the scan object seems to be completely skipped and dose not read at all just moves to the next line and continues.
name = scan.nextLine(); //getting skiped
System.out.println("Enter number of days in Hospital: ");
days = scan.nextInt();
System.out.println("Enter Room type(P, S, W): ");
room = scan.next();
System.out.println();
System.out.println();
if(!((room.equalsIgnoreCase("P")) || (room.equalsIgnoreCase("S")) || (room.equalsIgnoreCase("W"))))
{
System.out.println("Incorect room information");
System.out.println("Please enter P, S, or W for room selection");
System.out.println();
patientBillingInfo();
}
else
{
if(room.equalsIgnoreCase("P"))
totalPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("S"))
totalSemiPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("W"))
totalWardRoomCharges += 1*days;
totalTelephoneCharges += 1*days;
totalTelevisionCharges += 1*days;
patient = new Patient(name, days,room);
}
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Statement");
System.out.println();
System.out.println("Patient's name: " + patient.getName());
System.out.println("Number of days in Hospital: " + patient.getDays());
System.out.println();
System.out.println("Room charge $ " + patient.getRoomCharge());
System.out.println("Telephone charge $ " + patient.getTelephoneCharge());
System.out.println("Television charge $ " + patient.getTelevisionCharge());
System.out.println();
System.out.println("Total charge $ " +patient.getTotalCharge());
System.out.println();
System.out.println();
mainMenu();
}
// precondition: none
// postcondition: a summary report is printed that includes the daily total
// room charges for each type of room, the daily total telephone charges,
// and the daily total television charges. The report also includes the
// total receipts for the day.
public void printSummaryReport()
{
double tPRC = 225.0*totalPrivateRoomCharges;
double tSPRC = 165.0*totalSemiPrivateRoomCharges;
double tWRC = 95.0*totalWardRoomCharges;
double tTpC = 1.75*totalTelephoneCharges;
double tTvC = 3.50*totalTelevisionCharges;
double tR = tPRC+tSPRC+tWRC+tTpC+tTvC;
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Daily Billing Summary");
System.out.println();
System.out.println("Room Charges");
System.out.println(" Private: $" + tPRC);
System.out.println(" Semi-Private: $" + tSPRC);
System.out.println(" Ward: $" + tWRC);
System.out.println("Telephone Charges: $" + tTpC);
System.out.println("Telvision Charges: $" + tTvC);
System.out.println();
System.out.println("Total Receipts: $" + tR);
System.out.println();
}
}
edit: so it just occurred to me that maybe just maybe the rest of the code that this goes with might be useful dunno why I didn't think about this sooner but here's the rest
the class that actually runs
public class Administrator
{
public static void main(String[] args)
{
Hospital hospital = new Hospital();
}
}
and the class that works the patient info
public class Patient
{
//--- Constants
public final double PRIVATE = 225.00;
public final double SEMI = 165.00;
public final double WARD = 95.00;
public final double TELEPHONE = 1.75;
public final double TELEVISION = 3.50;
//--- Instance Variables
private String name;
private String roomType;
private int days;
//--- Constructors
public Patient(String n, int d, String rT)
{
name = n;
days = d;
roomType = rT;
}
//--- Methods
// precondition: none
// postcondition: returns the patient name
public String getName()
{
return name;
}
// precondition: none
// postcondition: returns the length of stay in days
public int getDays()
{
return days;
}
// precondition: none
// postcondition: returns the room type ("P", "S", "W")
public String getRoomType()
{
return roomType;
}
// precondition: none
// postcondition: returns the room charge which is dependant upon
// the room type and the length of stay.
public double getRoomCharge()
{
double charge = 0;
if(getRoomType().equalsIgnoreCase("P"))
charge = 225.00*getDays();
if(getRoomType().equalsIgnoreCase("S"))
charge = 165.00*getDays();
if(getRoomType().equalsIgnoreCase("W"))
charge = 95.00*getDays();
return charge;
}
// precondition: none
// postcondition: returns the telephone charge which is dependant upon
// the length of stay
public double getTelephoneCharge()
{
double charge = 1.75*getDays();
return charge;
}
// precondition: none
// postcondition: returns the television charge which is dependant upon
// the length of stay
public double getTelevisionCharge()
{
double charge = 3.50*getDays();
return charge;
}
// precondition: none
// postcondition: returns the total charge which is the sum
// of the room charge, telephone charge, and television charge.
public double getTotalCharge()
{
double charge = getRoomCharge()*getTelephoneCharge()+getTelevisionCharge();
return charge;
}
}
really don't know why it didn't occur to me sooner to do this but whatever live and lern right
You could simply scan a line and then parse it as the integer for Integer values.
so for reading integers instead of
val=scan.nextInt()
you could use
String strVal = scan.nextLine();
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
//maybe try again, or break the code ... or proceed as you wish.
}
this is because the nextInt() does not take the "Enter" key into account, and when you press enter after the nextInt() the int is read into the variable expecting nextInt() and the "Return" Key is accepted by the nextLine() which results in an empty line being read into the variable.
In public void mainMenu() you need to add scan.nextLine(); after ans = scan.nextInt(); in order to clear the rest of the input buffer.
ans = scan.nextInt();
scan.nextLine(); // <----- Add this line here
I have just started learning Java in the last week or so and I'm creating a program that acts as a sales calculator that calculates commission.
My code is as follows:
import java.util.Scanner;
public class Application {
int itemOne;
int itemTwo;
int itemThree;
int itemFour;
final double baseCommission = 200;
final double itemOnePrice = 239.99;
final double itemTwoPrice = 129.75;
final double itemThreePrice = 99.95;
final double itemFourPrice = 350.89;
final double commissionPercentage = 0.09;
boolean startLoop = false;
public void start(){
while (startLoop = false);
{
//Welcome message
System.out.println("Welcome to Devon's Sales Calculator!");
//Defining new scanner
Scanner user_input = new Scanner(System.in);
//Getting user input for salesperson name along with number of items sold as well as assigning them to a variable
String salesman_name;
System.out.print("Insert salesperson name:\t");
salesman_name = user_input.next();
System.out.print("Enter number of first item sold:\t");
int first_item = user_input.nextInt();
System.out.print("Enter number of second item sold:\t");
int second_item = user_input.nextInt();
System.out.print("Enter number of third item sold:\t");
int third_item = user_input.nextInt();
System.out.print("Enter number of fourth item sold:\t");
int fourth_item = user_input.nextInt();
//Printing out the name of the salesmen, followed by the total price of items sold
System.out.println("Sales Person\t" + salesman_name);
System.out.println("Total price of first item sold\t" + first_item * itemOnePrice);
System.out.println("Total price of second item sold\t" + second_item * itemTwoPrice);
System.out.println("Total price of third item sold\t" + third_item * itemThreePrice);
System.out.println("Total price of fourth item sold\t" + fourth_item * itemFourPrice);
//Calculating total of all items sold
double finalPrice = first_item * itemOnePrice + second_item * itemTwoPrice + third_item * itemThreePrice + fourth_item * itemFourPrice;
//Calculating commission # 0,9%
System.out.println("Total commission earned\t" + finalPrice * commissionPercentage);
//Decision whether or not to restart the while loop
String decision;
System.out.println("Would you like to check another salesperson?");
decision = user_input.next();
if(decision == "yes"){
startLoop = false;
}
else if(decision == "no"){
startLoop = true;
}
}
}
}
Whenever I execute my while loop, it doesn't restart to choose another salesman. I'm probably doing something horribly wrong and my code formatting is probably horrible. Any help would be appreciated.
Get rid of the = false and the semicolon. So not:
while (startLoop = false);
{
System.out.println("foo");
}
which is equivalent to
while (startLoop = false) {
// do nothing
}
{
System.out.println("foo");
}
Instead do,
while (!startLoop) {
// do something here
}
I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.
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;
}
}