Write a method calcDiscount that accepts two parameters: a double price and a char representing a discount code and returns a double representing the amount of the discount
Compute the amount of the discount given the following table of discount codes:
A 5%
D 10%
N 15%
E 20%
If the discount code is not A, D, N, or E, the discount returned should be 0. Note that you are NOT returning the discounted price, but the actual amount of the discount, so calling calcDiscount with 5.00 and D as arguments should result in an answer of 5.00
I tried the code, and I think its what I need per the instructions, but I cant get the method to print out.
package edu.ilstu;
import java.util.Scanner;
public class ClassOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a price");
double price = scan.nextDouble();
System.out.println("Enter a discount code");
char c = scan.next().charAt(0);
}
public static double calcDiscount(double price, char c) {
switch (c) {
case 'A':
double a = (price * .05);
return a;
case 'D':
double d = (price * .10);
return d;
case 'N':
double n = (price * .15);
return n;
case 'E':
double e = (price * .20);
return e;
default:
double z = 0;
return z;
}
System.out.println(ClassOne.calcDiscount());
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a price");
double price = scan.nextDouble();
System.out.println("Enter a discount code");
char c = scan.next().charAt(0);
double discount = calcDiscount(price, c);
System.out.println("Discount: " + discount);
}
You should call the calcDiscount method from your main method. The print statement at the end of the calcDiscount method is incorrect.
Related
I thought using += the total will sum the result , but he reset everything after I insert again.
import java.util.Scanner;
public class Week3_Lab {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int product;
int amount;
while(true){
System.out.print("Enter the product number(1-3): ");
product = input.nextInt();
if (product == -1){
break;
}
System.out.print("Enter the total amount of product: ");
amount = input.nextInt();
num(product, amount);
}
}
public static int num(int product , int amount){
double total_1 = 0;
double total_2 = 0;
double total_3 = 0;
switch (product){
case 1 :
total_1 += amount * 2.98;
break;
case 2 :
total_2 += amount * 4.50;
break;
case 3 :
total_3 += amount * 9.98;
break;
}
System.out.println("The total of product 1 is : "+ total_1);
System.out.println("The total of product 2 is : "+ total_2);
System.out.println("The total of product 3 is : "+ total_3);
return product;
}
}
Your variables total_1, total_2 and total_3 are local and not shared between method calls and therefore for each call be initialized to 0.
If you don't want this to happen define them outside of the method body.
static double total_1=0;
static double total_2=0;
static double total_3=0;
public static int num(int product , int amount){
switch (product){
//...
}
//...
}
You have initialized your total_1 to 0, so the program is output is simply (amount * 2.98) as shown below:
total_1 = 0 + (amount * 2.98);
The same concept is applied for total_2 and total_3 as well.
Orphaned Case Error
The following are the tasks which will be done in the program:-
Accept Deposit from a customer and update the balance.
Display the balance.
Compute and deposit the compound interest.
Permit withdrawal and update the balance.
Check for the minimum balance, impose penalty, if necessary and update the balance
I am getting an "orphaned case" error for
case1: S1.Display();
case1: S2.Display();
Please help. This is the Code:
import java.util.*;
class Account
{
String custname;
double accno;
double bal;
Account(String c, double a, double b)
{custname = c;
accno = a;
bal = b;
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
System.out.println("Balance : "+bal);
}
void Deposit()
{double dep;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter the amount your want to deposit:");
dep = sc.nextDouble();
bal = bal + dep;
System.out.println("Updated Details....");
Display();
}
void Withdraw()
{double wth;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount you want to withdraw");
wth = sc.NextDouble();
bal = bal - wth;
System.out.println("Updated details....");
Display();
}
}
class SavAccount extends Account
{ String acctype;
SavAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Savings";
}
void ComInt()
{int months;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the duration of the account in months");
months = sc.NextInt();
double rate, inte;
rate = 0.04;
inte = months *rate * bal;
bal = bal + inte;
System.out.println("Compund Interest : "+inte);
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
ComInt();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
}
}
class CurAccount extends Account
{String acctype;
CurAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Current";
}
void Penalty()
{
if(bal<5000.00)
{bal = bal - 100.00;
System.out.println("Fine deducted Rs.100/-");
}
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
Penalty();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
if(bal<=5000.00)
{System.out.println("Warning!! Please maintain balance above Rs.5000/-");
}
}
}
class Accmain
{public static void main(Strings args[])
{SavAccount S1 = new SavAccount("Aniruddha", 134.00, 15000.00)
;
CurAccount S2 = new CurAccount("Tyrel" , 135.00, 6000.00);
int num = 2;
String c = "y";
int n;
double temp;
double accs[] = new double[10];
accs[0] = S1.accno;
accs[1] = S2.accno;
Scanner sc = new Scanner(System.in);
while (c == "y");
{System.out.println("Please enter your Account number:");
temp = sc.nextDouble();
if(accs[0] == temp)
{System.out.println("Welcome "+ S1.custname);
System.out.println("Account Type: "+ S1.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt();
Switch(n)
;
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
else if(accs[1] == temp)
{System.out.println("Welcome "+ S2.custname);
System.out.println("Account Type: "+ S2.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt()
;
Switch(n);
{
case 1 : S2.Display();
case 2 : S2.Withdraw();
case 3 : S2.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
}
}
}
Several problems.
1) That extra ; in the end made the switch completed right away on that stamtement.
Switch(n); <--
Apparently all the cases became orphans.
If you remove the colon after Switch(n) you would be fine.
Switch(n)
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
2) After that you have another problem. You need to have break after each case. Otherwise your switch executes all the cases even though the match found. To stop that add break after each case
Switch(n)
{
case 1 : S1.Display(); break;
case 2 : S1.Withdraw();break;
...
3) When you write c == "y" That compare references not equality.
you need to use equals() method to check string equality
read How do I compare strings in Java?
4) That line Super(c, a, b); won't compile as S must be lower-case. Java is case sensitive.
The two problems you're hitting are:
Switch(n) // <-- switch is not spelled with a capital 's'
; // <-- remove the semicolon
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
Since the cases appear without any relation to a switch - you're getting the "Orphaned Case Error". Further, when you're done handling each case you should break; otherwise the code will continue executing the following cases as well!
I would also advise you to use a good IDE and auto-indent the code because the way it is currently indented makes it very difficult to see where an if or else clauses ends.
A good IDE (IntelliJ/Eclipse/Netbeans) will also show you all the compilation errors you have, for example Super(c, a, b) - the 's' should not be capitalized, and etc.
This error usually meas that you are trying to use a case keyword outside of a switch statement.
Switch(n)
;
here after switch(n) remvoe the ;
also use break statement after each case operations. else it will keep executing the next case operations.
other minor issues are mentioned in Sures's answer
case 1:System.out.println("1111111111111111");
some example case 1:System no spaces in statement
example case 1:System.out.println("Display the vales");
I know that in method headers you aren't supposed to end it with a semicolon; however, all my method headers display the same error: ; expected. This is for the end of the header as well as between two parameters. How would I fix this?
import java.util.Scanner;
import java.text.DecimalFormat;
// This program will calculate the cost of someone's order at a coffee shop with applied possible discounts and tax
public class CoffeeShopWithMethods
{
public static void main (String [] args)
{
double cost = 0;
double discount = 0;
// Scanner allows user to enter values
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("\nEnter your username: ");
username = user_input.next( );
System.out.print ("\nWelcome to Casey's Classic Coffee, " + username + "! \n");
//call methods
displayMenu();
displayOutput(cost, discount, Discounted_cost, tax, Total_cost);
System.out.println("\nThank you " + username + "! Have a nice day!");
}
//outputs the menu to the screen
public static void displayMenu()
{
System.out.println ("\n\tItem\t\tCost\n\t1. Coffee\t$1.50\n\t2. Latte\t$3.50\n\t3. Cappuccino\t$3.25\n\t4. Espresso\t$2.00");
}
//prompts the user to enter item number, returns user input
public static int getItemNumber(int number) //error: ; expected
{
int number;
Scanner number = new Scanner(System.in);
System.out.print ("\nPlease enter the desired item number: ");
number = user_input.nextInt();
return number;
}
//prompts user to enter quantity, returns user input
public static int getQuantity (int quantity) //error: ; expected
{
System.out.print ("\nPlease enter the quantity: ");
quantity = user_input.nextInt();
return quanity;
}
//takes the item number and quantity and returns the subtotal
public static double computeSubTotal (double cost) //error: ; expected
{
int number = getItemNumber(number);
int quantity = getQuantity(quantity);
// Used final double in order to make coffee shop items constant
final double COFFEE = 1.50;
final double LATTE = 3.50;
final double CAPPUCCINO = 3.25;
final double ESPRESSO = 2.00;
double cost = 0;
if (number == 1)
cost = quantity * COFFEE;
else if (number == 2)
cost = quantity * LATTE;
else if (number == 3)
cost = quantity * CAPPUCCINO;
else if (number == 4)
cost = quantity * ESPRESSO;
}
//takes the subtotal and returns true if the user earned a discount; otherwise, returns false
public static boolean discountCheck (double cost) //error: ; expected
{
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
//takes the subtotal and returns the dollar amount of the discount earned by the user
public static double computeDiscount (double cost, double discount) //error: ; expected
{
if (discountCheck() == true)
{
discount = cost * 0.10;
}
else if (discountCheck() != true)
{
discount = 0;
}
return discount;
}
//takes the subtotal and the discount amount and returns the price after the discount is applied
public static double computePriceAfterDiscount (double cost, double discount) //error: ; expected
{
double discount = 0;
double Discounted_cost = 0;
Discounted_cost = cost - discount;
return Discounted_cost;
}
//takes the prices after the discount is applied and tax rate and returns the tax amount
public static double computeTax(double Discounted_cost) //error: ; expected
{
tax = Discounted_cost * 0.07;
return tax;
}
//takes the price after the discount is applied and the tax amount and returns the final total
public static double computeTotal(double Discounted_cost, double tax) //says ; expected
{
Total_cost = Discounted_cost + tax;
return Total_cost;
}
//takes the subtotal, discount amount, price after discount, tax, and final total and displays all the lines of output to the user
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost) //says ; expected at the end of method header
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
} //error:reached end of the file while parsing
1)You are using the variables with out declaring:
for eg: compare this snippet with your code snippet.
public static double computeTotal(double Discounted_cost, double tax)
{
double Total_cost = Discounted_cost + tax;
return Total_cost;
}
2)You are invoking undefined methods.
for eg:
you are calling discountCheck() but you have defined like this.
and you have not initialized local variables before using
public static boolean discountCheck (double cost){
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
in the above method status should be initialized.
3) You are declaring duplicate variables that are already available to the methods via parameters.
see the code defined by you here:
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost)
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
I would start by extracting your MenuItem(s) into an enum like,
static enum MenuItem {
COFFEE("Coffee", 1.5), LATTE("Latte", 3.5), CAPPUCINO("Cappuccino",
3.25), ESPRESSO("Espresso", 2);
MenuItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
double cost;
String name;
public String toString() {
return String.format("%s $%.2f", name, cost);
}
}
Then your compiler errors were mainly due to declaring duplicate local variable names. I was able to fix the compiler errors and produce something that looks like what you want with,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scan.nextLine();
System.out.printf("Welcome to Casey's Classic Coffee, %s!%n", username);
displayMenu();
displayOutput(scan);
System.out.printf("Thank you %s! Have a nice day!", username);
}
// outputs the menu to the screen
public static void displayMenu() {
MenuItem[] items = MenuItem.values();
for (int i = 0; i < items.length; i++) {
System.out.printf("%d %s%n", i + 1, items[i]);
}
}
public static int getItemNumber(Scanner scan) {
System.out.println("Please enter the desired item number: ");
return scan.nextInt();
}
public static int getQuantity(Scanner scan) {
System.out.println("Please enter the quantity: ");
return scan.nextInt();
}
public static double computeSubTotal(Scanner scan) {
int number = getItemNumber(scan);
int quantity = getQuantity(scan);
return quantity * MenuItem.values()[number - 1].cost;
}
public static boolean discountCheck(double cost) {
return (cost >= 10);
}
public static double computeDiscount(double cost) {
if (discountCheck(cost)) {
return cost * 0.10;
}
return 0;
}
public static double computePriceAfterDiscount(double cost, double discount) {
return cost - discount;
}
public static double computeTax(double Discounted_cost) {
return Discounted_cost * 0.07;
}
public static double computeTotal(double Discounted_cost, double tax) {
return Discounted_cost + tax;
}
public static void displayOutput(Scanner scan) {
double cost = computeSubTotal(scan);
double discount = computeDiscount(cost);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf("Total before discount and tax: $%.2f%n", cost);
System.out.printf("Calculated discount: $%.2f%n", discount);
System.out.printf("Total after special discount: $%.2f%n",
Discounted_cost);
System.out.printf("Tax: $%.2f%n", tax);
System.out.printf("Total cost: $%.2f%n", Total_cost);
}
Here is your entire code corrected and working: http://ideone.com/ta0R21
I really recommend redesigning this. I suggest making use of global variable in some instances.
like the Scanner object. Instead of initializing a new Scanner each method call, use a global
one to handle the entire job
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}
I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}