Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to find a java code to my calculation below,
can't find how to increment the value by 53 and 79 ,
public static void main(String[] args) {
int weight, b;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Weight : ");
weight = (int) sc.nextDouble();
b = calculateLandingRate(weight);
System.out.println("Total price : " + b);
}
static int calculateLandingRate(int weight) {
int rate = 26;
if (weight<= 25) {
if (weight > 1) {
int totalPrice = 26 * weight;
} else if (weight> 25 && weight < 75) ;`
total price= (the weight 26kg ) + 53 ,
the calculation should be like the value is incremented by 53 ,from the weight =26kg
/* int rate = +53;
Total price at 26kg = 650 + 53 =703
Total price at 27kg = 703 + 53=756
Total price at 28kg = 756 + 53 =809
Total price at 29kg = 809 + 53 =862
Total price at 30kg = 862 + 53 =915
*
*
*
Total price at 75kg = 3247 + 53 =3300
*/
}
else if (weight > 75) ;
the value increment by 79
int rate = +79;
Total price at 76kg = 3300 + 79 =3379
*
*
*
*
Total price at 624 kg = 46592 + 79 =46671
I think what you are after is this
static int calculateLandingRate(int weight) {
int lowRate = 26;
int midRate = 53;
int highRate = 79;
int lowRateLimit = 25;
int midRateLimit = 75;
int totalPrice = 0;
if (weight > 1 && weight <= lowRateLimit) {
totalPrice = lowRate * weight;
} else if (weight > lowRateLimit && weight <= midRateLimit) {
totalPrice = lowRate * lowRateLimit + midRate * (weight - lowRateLimit);
} else if (weight > midRateLimit) {
totalPrice = lowRate * lowRateLimit + midRate * (midRateLimit - lowRateLimit) + highRate * (weight - midRateLimit);
}
return totalPrice;
}
Remarks:
Your elseif statement else if (weight> 25 && weight < 75) is always false
you define rate but do not use it
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int weight, b;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the weight : ");
weight = sc.nextInt();
b = calculateLandingRate(weight);
System.out.println("Total price : " + b);
}
static int calculateLandingRate(int weight) {
final int RATE = 26;
final int LOWERLIMIT = 25;
final int LOWERLIMITADDER = 53;
final int UPPERLIMIT = 75;
final int UPPERLIMITADDER = 79;
// Base price
int price = LOWERLIMIT * RATE;
if (weight > 25 && weight <= 75) {
price += LOWERLIMITADDER * (weight - LOWERLIMIT);
} else if (weight > 75) {
price += LOWERLIMITADDER * (UPPERLIMIT - LOWERLIMIT);
price += UPPERLIMITADDER * (weight - UPPERLIMIT);
}
return price;
}
}
A sample run:
Enter the weight : 24
Total price : 650
Another sample run:
Enter the weight : 25
Total price : 650
Another sample run:
Enter the weight : 40
Total price : 1445
Another sample run:
Enter the weight : 74
Total price : 3247
Another sample run:
Enter the weight : 75
Total price : 3300
Another sample run:
Enter the weight : 80
Total price : 3695
Another sample run:
Enter the weight : 624
Total price : 46671
Related
I am trying to figure out how to use the string.format feature into the return statement. Each line has to be a system out? so that means ill have 3 seperate system out?
/*
0 - 4 miles = $2
5 - 15 miles = $5
16 - 25 miles = $10
26 - 50 miles = $15
More than 50 miles = $20
WRITE A PROGRAM THAT CALCULATES TOTAL COST OF USER'S ITEMS
YOUR OUTPUT SHOULD BE FORMATTED AS SEEN BELOW!!
Product Qty Price Miles Total
---- --- ----- ----- -----
Rice 20 5.0 10.0 105.0
Thank you. Come Again!!!
*/
Above is the format that is wanted, I was able to create a method that calculates and returns the correct values, i just need to format the string variable receipt.
public class Test {
public static void main(String[] args) {
methods Rice = new methods();
methods Beans = new methods();
System.out.println(Rice.getTotal("Rice",20,5.0,10));
System.out.println("\n"+ Beans.getTotal("Cake",200,5.75,102.78));
}
}
public class methods {
int qty;
double price;
double miles;
double total;
int i;
String product;
String receipt;
public String getTotal(String product, int qty, double price, double miles){
// 0 - 4 miles = $2
// 5 - 15 miles = $5
// 16 - 25 miles = $10
// 26 - 50 miles = $15
// More than 50 miles = $20
this.qty = qty;
this.price=price;
this.miles = miles;
this.total = 0;
this.product = product;
for(i = 0; i < miles; i++){
if(i < 5){
total = qty * price + 2;
}
else if(i > 4 && i < 16){
total = qty * price + 5;
}
else if(i > 15 && i < 26){
total = qty * price + 10;
}
else if(i > 25 && i < 51){
total = qty * price + 15;
}
else if(i > 50 ){
total = qty * price + 20;
}
}
//return
}
}
I commented out the return statement where the code should go. I can use print method or string.format method.
I'm trying to increment the values inside of an array that corresponds to how many times that discount has been used. The incrementation works well if the discount is 0% (discount = 1.0) but for 20%, 30%, and 40% (discount is 0.8, 0.7, 0.6 respectively) the related index in the counts array is incremented by 2. Finally, if discount = 0.5 counts[4] is incremented by 8. I feel like it has something to do with what iteration of the for loop I'm in but I can't figure it out.
Heres the class that I think holds the problem:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package softwaresales;
/**
*
* #author python
*/
public class SoftwareSales {
private int unitsSold;
private final double UNIT_PRICE = 99.0;
private final int[] UNITS_LOW_RANGES = {1, 10, 20, 50, 100};
private final double[] DISCOUNTS = {1.0, 0.8, 0.7, 0.6, 0.5};
private static int[] counts = {0, 0, 0, 0, 0};
SoftwareSales(int u){
unitsSold = u;
}
public int getUnitsSold(){
return unitsSold;
}
public double getDiscount(){
double discount = 1;
for (int i = 0; i < 4; i++){
if((unitsSold >= UNITS_LOW_RANGES[i]) &&
(unitsSold < UNITS_LOW_RANGES[i+1])){
counts[i] += 1;
discount = DISCOUNTS[i];
}
else if (unitsSold >= 100){
counts[4] += 1;
discount = DISCOUNTS[4];
System.out.print("*");
}
}
return discount;
}
public double getCost(){
return unitsSold * UNIT_PRICE * getDiscount();
}
public int[] getCounts(){
return counts;
}
}
Here's a sample input :
13
31
115
101
96
8
29
103
27
129
And the related output:
Units sold: 13
Discount: 19.999999999999996%
Price: $1029.6000000000001
Units sold: 31
Discount: 30.000000000000004%
Price: $2148.2999999999997
Units sold: 115
Discount: 50.0%
Price: $5692.5
Units sold: 101
Discount: 50.0%
Price: $4999.5
Units sold: 96
Discount: 40.0%
Price: $5702.4
Units sold: 8
Discount: 0.0%
Price: $792.0
Units sold: 29
Discount: 30.000000000000004%
Price: $2009.6999999999998
Units sold: 103
Discount: 50.0%
Price: $5098.5
Units sold: 27
Discount: 30.000000000000004%
Price: $1871.1
Units sold: 129
Discount: 50.0%
Price: $6385.5
=================
= =
= DISCOUNTS =
= =
=================
0% discounts: 1
20% discounts: 2
30% discounts: 6
40% discounts: 2
50% discounts: 32
As you can see there is only one instance where a 0% discount was given which is represented in the output. There is also only one instance each of 20% and 40% discounts but the output shows 2 for each, similar to the 30% discount. Also there was 4 instances of a 50% discount being given, but as you can see the array was incremented 32 times...
Here's my main program where I call getDiscount().
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package softwaresales;
import java.io.*;
import java.util.Scanner;
/**
*
* #author python
*/
public class SofwareSalesDriver {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String file_location;
Scanner kb = new Scanner(System.in);
CreateInputFile inputs = new CreateInputFile();
System.out.println("Enter the PATH to the folder where you would like" +
" the in/out files: ");
System.out.println("\nExamples:\nLinux: /home/%USER_NAME%/Documents/" +
"\nor Windows: C:\\\\users\\\\%USER_NAME%\\\\Documents\\\\");
System.out.print("\nEnter PATH: ");
file_location = kb.nextLine();
String infile = file_location + "Inputs.txt";
String outfile = file_location + "Outfile.txt";
File file = new File(outfile);
FileWriter writer = new FileWriter(file);
int unitsSold = 0;
SoftwareSales customer = new SoftwareSales(unitsSold);
int[] counts = customer.getCounts();
inputs.createInputFile(file_location);
Scanner fileLine = new Scanner(new File(infile));
while (fileLine.hasNextInt()){
unitsSold = fileLine.nextInt();
customer = new SoftwareSales(unitsSold);
writer.write("Units sold: " + unitsSold + "\n" +
"Discount: " + (1 - customer.getDiscount())*100 + "%\n" +
"Price: $" + customer.getCost() + "\n\n");
}
writer.write("=================\n= =\n" +
"= DISCOUNTS =\n= =\n" +
"=================\n" +
"0% discounts: "+ counts[0] / 2 +
"\n20% discounts: " + counts[1] +
"\n30% discounts: " + counts[2] +
"\n40% discounts: " + counts[3] +
"\n50% discounts: " + counts[4] + "\n\n");
writer.close();
}
}
If I get your code correctly, the error is related to the if-statement in your for loop. You should have the check before the for loop, otherwise you increment the counter multiple times per loop if unitsSold >= 100 because the else statement is called for each loop iteration.
if (unitsSold >= 100){
counts[4] += 1;
discount = DISCOUNTS[4];
System.out.print("*");
} else {
for (int i = 0; i < 4; i++){
if((unitsSold >= UNITS_LOW_RANGES[i]) &&
(unitsSold < UNITS_LOW_RANGES[i+1])){
counts[i] += 1;
discount = DISCOUNTS[i];
}
}
}
The reason for the double counting of some numbers is due to that function:
public double getCost(){
return unitsSold * UNIT_PRICE * getDiscount();
}
Here, you call getDiscount() again, which will again trigger the whole process and add the respective value to counts[i].
I would recommend you the following: Instead of calculating the discount twice, you could just pass the discount as a parameter like getCost(double discount).
This way, you prevent calling this function twice.
Just a quick notice at the end: Normally, you should refrain from performing modifications of global variables in getters if you do not intend to actually count the number of getter-calls. Probably, the discount calculation could be moved to the constructor and the getDiscount() only returns the discount that has been previously calculated in the constructor. But that just as a side note.
Foo Corporation needs a program to calculate how much to pay their hourly employees.
The US Department of Labor requires that employees get paid time and a half for any hours over 40 that they work in a single week.
For example, if an employee works 45 hours, they get 5 hours of overtime, at 1.5 times their base pay.
The State of Massachusetts requires that hourly employees be paid at least $8.00 an hour.
Foo Corp requires that an employee not work more than 60 hours in a week.
An employee gets paid (hours worked) × (base pay), for each hour up to 40 hours. For every hour over 40, they get overtime = (base pay) × 1.5. The base pay must not be less than the minimum wage ($8.00 an hour). If it is, print an error. If the number of hours is greater than 60, print an error message.
Create a new class called FooCorporation.
Write a method that takes the base pay and hours worked as parameters, and prints the total pay or an error. Write a main method that calls this method for each of these employees:
Base Pay Hours Worked Employee 1 $7.50 35 Employee 2 $8.20 47 Employee 3 $10.00 73
You have to read base pay and hours from a text file in this format.
Employee, basePay, hours
1, 8, 40,
2, 9, 33,
3, 10, 70
Here is my code:
package foocorporation;
public class FooCorporation {
double minimumWage = 8.0;
int maxHours = 60;
float x;
int y;
public static void main(String[] args) {
salaryCalculation(x,y, minimumWage, maxHours);
salaryCalculation(x,y, minimumWage, maxHours);
salaryCalculation(x,y, minimumWage, maxHours);
}
public static void salaryCalculation
(double basePay, int hoursWorked, double minimumWage, int maxHours){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}
have a look at this
UPDATE
if you want to take the input from the user as you asked later
public class FooCorporation {
static final double minimumWage = 8.0; // static means that can be accessed without creating an object of the class and instantiating it
static final int maxHours = 60; // final means constant = cannot be changed after declared
static double basePay=0; // initialize them to zero, at least you know your program won't throw null pointer exception if forgot to set their
//values before invoking the method
static int hoursWorked=0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int i=1; i<=3; i++, System.out.println()){
System.out.println("For Employee Number: " + i);
System.out.println("Enter Base Pay:");
basePay = in.nextDouble();
System.out.println("Enter Hours Worked:");
hoursWorked = in.nextInt();
salaryCalculation();
}
}
public static void salaryCalculation(){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}
result will be for your inputs for example:
For Employee Number: 1
Enter Base Pay:
7.5
Enter Hours Worked:
35
Error!
For Employee Number: 2
Enter Base Pay:
8.2
Enter Hours Worked:
47
Your total salary is 414.1
For Employee Number: 3
Enter Base Pay:
10
Enter Hours Worked:
37
Your total salary is 370.0
package foocorporation;
public class Foocorporation {
final static double minimumWage = 8.0;
final static int maxHours = 60;
public static void main(String[] args) {
float x;
int y;
x=7.5f;
y=35;
salaryCalculation(x,y);
x=8.2f;
y=47;
salaryCalculation(x,y);
x=10.0f;
y=73;
salaryCalculation(x,y);
}
public static void salaryCalculation(double basePay, int hoursWorked){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}
The question says The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per 500 Miles Shipped
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
The shipping charge per 500 miles are not prorated. For example, if a 2-pound package is shipped 550 miles, the charges would be $2.20. Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
My problem is that I keep receiving two different answers everytime I put in a weight and distance. For example when I enter the weight as 2 pounds and the distance as 500 miles I get the answers $0.0 and $3.8 which are both incorrect answers. It looks like some weights that I enter are correct answers and others I enter give me incorrect answers. Heres my program:
//import java utilities for scanner class
import java.util.Scanner;
public class ShippingCharge
{
public static void main (String[] args)
{
//Declare and initialize variable to hold the entered weight.
int weight = 0;
//Declare and initialize variable to hold the entered distance.
double distance = 0.0;
//This variable will hold the calculated rate.
double rate;
//This will decide if the shipping charge will advance up one level.
int distanceMultiplier = (int)distance / 500;
//This will hold the increments of the shipping charge.
int distanceRemainder;
//Create a Scanner object for the input.
Scanner input = new Scanner(System.in);
//Get the weight of the package.
System.out.println("What is the weight of the package (in pounds)?");
weight = input.nextInt();
//Get the shipping distance of the package.
System.out.println("What is the shipping distance (in miles)?");
distance = input.nextDouble();
distanceRemainder = (int)distance % 500;
if (distanceRemainder == 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.70));
}
else
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.80));
}
if (distanceRemainder != 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.70);
}
else
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.80);
}
//end program
System.exit(0);
}//end main
}//end class
This will work for you
public static void main(String[] args) {
int weight = 0;
double distance = 0.0 , distanceExtra ;
Scanner in = new Scanner(System.in);
System.out.println("Weight ? ");
weight = in.nextInt();
System.out.println("Distance ? ");
distance = in.nextDouble();
distanceExtra = distance / 500;
distanceExtra = Math.ceil(distanceExtra);
if (weight <= 2) {
System.out.printf("charge is :" , (distanceExtra * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.printf("charge is :" , (distanceExtra * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.printf("charge is :" , (distanceExtra * 3.70));
}
else if (weight > 10)
{
System.out.printf("charge is :" , (distanceExtra * 4.80));
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int weight = 0;
double distance = 0.0 ;
Scanner keyboard =new Scanner(System.in);
System.out.println("Enter the Distance");
distance = keyboard.nextDouble();
System.out.println("Enter the Weight");
weight = keyboard.nextInt();
if (weight <= 2) {
System.out.println("charge is : " + "$"+1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("charge is : " + "$"+2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("charge is : " + "$"+3.70);
}
else if (weight > 10)
{
System.out.println("charge is :" + "$"+4.80);
}
}
}
I am trying to replicate a list of conversions from kg to lbs and vice versa. I've found my desired code for output and functionality, but I am missing something to align my values to the right of the column.
Here is my code:
import java.text.*;
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.println("Kilograms" + "\t" + "Pounds" + "\t" + " | " + "\t" + "Pounds" + "\t" + "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%-17d %.1f | %7d %.2f%n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
I am also trying to create a break in the list three rows in and resume the last two.
The problem is that you are not specifying a width for the float values, just the number of decimal places.....
For example, consider "%-17d %.1f ..." which will set the second value to be a float value with 1 decimal place, but no indication of how much space to occupy. By changing that to "%-17d %12.1f it will occupy 12 characters, with 1 decimal.
Try something like:
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.printf("%12s %12s | %7s %12s\n", "Kilograms", "Pounds", "Pounds", "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%12d %12.1f | %7d %12.1f\n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
For me, the above process outputs:
Kilograms Pounds | Pounds Kilograms
1 2.2 | 20 9.1
3 6.6 | 25 11.3
....
199 437.8 | 515 233.3