phillip swag phillip swag - 3 months ago 6
Java Question

Gettin wrong results

when i put in 10 packages i get the correct results but when i put in 58, i get the wrong results.

My output:

Enter the number of packages purchased: 58
Your total without discount: 5742.0
The discount is: 1148.4
The discounted total: 4593.6


What it should have:

Enter the number of packages purchased: 58
Your total without discount: 5742.0
The discount is: 2411.6
The discounted total: 3330.3




package pkg;

import java.util.Scanner;

public class Hello {
public static void main(String[] args) {
double packageCost = 99.00;
Scanner user_input = new Scanner(System.in);
System.out.print("Enter the number of packages purchased: ");
int askPackage = user_input.nextInt();
double withoutDiscount = packageCost * askPackage;
double firstDiscount = (packageCost * askPackage) - (withoutDiscount * .20);
double secondDiscount = (packageCost * askPackage) - (withoutDiscount * .33);
double thirdDiscount = (packageCost * askPackage) - (withoutDiscount * .42);
double fourthDiscount = (packageCost * askPackage) - (withoutDiscount * .49);
System.out.println("Your total without discount: $" + withoutDiscount);
if (askPackage >= 10 || askPackage <= 19) {
System.out.println("The discount is: $" + withoutDiscount * .20);
System.out.println("The discounted total: $" + firstDiscount);
} else if (askPackage >= 20 || askPackage <= 49) {
System.out.println("The discount is: $" + withoutDiscount * .33);
System.out.println("The discounted total: $" + secondDiscount);
} else if (askPackage >= 50 || askPackage <= 99) {
System.out.println("The discount is: $" + withoutDiscount * .42);
System.out.println("The discounted total: $" + thirdDiscount);
} else if (askPackage >= 100) {
System.out.println("The discount is: $" + withoutDiscount * .49);
System.out.println("The discounted total: $" + fourthDiscount);
}
}
}

Answer

You should use && instead of || in your if else statements. All possible inputs are processed in your first condition askPackage >= 10 || askPackage <= 19 . Thus only inputs which are between 10-19 will give you true outputs.

P.S. You can do discount assignments like that:

double firstDiscount = (withoutDiscount * .80);

Or better solution; create a common discount variable and assign it in your if-else statements.