Alright so I'm trying to get the user to input either the word "random" or a number (0.01) for a sales tax and my prompt can only use either keybd.next() or keybd.nextDouble() so how would I easily do this?
public void calculateSalesReceipt(){
System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
double tax = keybd.nextDouble();
if(tax < 0){
System.out.println("You must enter a value equal to or greater than 0!");
}else{
getFinalPricePreTax();
total = total;
taxcost = total * tax;
double finaltotal = total * taxcost;
System.out.println("Sales Receipt");
System.out.println("-------------");
for(Item currentProduct : shoppingBag){
System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
}
System.out.println("Total cost: $" + total);
System.out.println("Total tax: $" + taxcost);
System.out.println("Total cost with tax: $" + finaltotal);
}
Thanks
Assuming keybd is a Scanner
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
You need to use hasNextDouble() to determine if it's a double or not and then act accordingly.
Option B (though you say your requirements exclude this) is to simply read it as a String then do the conversion afterward with Double.valueOf(String) or Double.parseString(String) static methods and catching the NumberFormatException to determine validity.
Edit based on comments from OP:
System.out.println("Enter the sales tax ... blah blah");
if (keybd.hasNextDouble())
{
double tax = keybd.nextDouble();
// Do double stuff
}
else
{
// Get String and Do string stuff
}
You can use Double.parseDouble(String) to convert a string value to a double. If the string does not represent a double value, a NumberFormatException will be thrown.
double d;
if ("random".equals(string)) {
d = 4.0; // random
} else {
try {
d = Double.parseDouble(string);
} catch (NumberFormatException e) {
// !
}
}
You can use keybd.next() to grab the token as a string. Then check if its a double.
Sample code:
String input= keybd.next();
try{
Double input= Double.parseDouble(input);
//execute code with double variable
} catch (ParseException ex){
//call string handler code
}
Related
this is my first question on the site. I am a fresh CS student needing some help with something that is probably really simple. The code as is will compile. When I enter in the values as the program asks, it stores the values wrong. It will store the right values for gross pay and savings rate but the IRA rate comes back as 100% even when entered at 6.9 and it seems it stores the IRA rate in saveAmount. Please halp me figure out what I am doing wrong here.
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
static Scanner console = new Scanner(System.in);
static DecimalFormat formatCash = new DecimalFormat("#,###.00");
static double iraTotal = 0.0;
static double saveAmount = 0.0;
static double totalSave = 0.0;
static String line = "";
public static void main (String [] args) {
// Input variables
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
String whichOne = ""; // A temp variable to pass a string type into UserInput
printInfo();
grossPay = userInput("gross pay");
saveRate = userInput("savings rate");
iraRate = userInput("IRA rate");
iraTotal = iraAmount(grossPay, iraRate);
saveAmount = savingsAmount(grossPay, saveRate);
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
return;
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public static double iraAmount(double grossPay, double iraRate) {
iraTotal = grossPay * (iraRate / 100.0);
return iraTotal;
} // End iraAmount
public static double savingsAmount(double grossPay, double saveRate) {
saveAmount = grossPay * (saveRate / 100.0);
return saveAmount;
} // End savingsAmount
public static void outputResults(double grossPay, double saveRate, double iraRate,
double saveAmount, double iraTotal) {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of $" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be $" + formatCash.format(saveAmount)
+ ", with a investment amount of $" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of $" +
+ totalSave + ". Way to go for paying yourself!" );
return;
} // End outputResults
} //End Class
Your only issue is the order of arguments you pass to or have set on the outputResults() method.
Change the signature of the method to:
public static void outputResults(double grossPay, double saveRate, double saveAmount, double iraRate, double iraTotal) {
Which now matches how you call the method:
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
Let me make a couple of additonal suggestions:
1) You are consistently naming arguments in your method signatures the same names as global variables, which makes it confusing which is which when accessing the variable in the method. Either avoid using the same names for the method input variables, or use something like this.amount = amount to make it more obvious of your intention.
2) Avoid static unless you have a valid reason to use it (which is pretty rare).
Instead, take advantage of Java's Object oriented nature and create an instance of your class in the main method and call methods on that instance. This will make your code more readable, reliable, and reusable.
3) In a method that returns type 'void', you don't need to add the empty return; statement.
To correct your issue and also demonstrate the points I listed, I have refactored your code and provided it below. By the way, you have a lot of potential. Despite the fact there are a few details you can improve, for being a first year CS student, your code is well written and thought out. Good job!
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
DecimalFormat formatCash = new DecimalFormat("#,###.00");
double iraTotal = 0.0;
double saveAmount = 0.0;
double totalSave = 0.0;
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
public CollinDunn_1_05(double gross, double saveRt, double iraRt){
this.grossPay = gross;
this.saveRate = saveRt;
this.iraRate = iraRt;
}
public void calculate(){
calcIraAmount();
calcSavingsAmount();
}
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
printInfo();
CollinDunn_1_05 program = new CollinDunn_1_05(
userInput("gross pay", scanner),
userInput("savings rate", scanner),
userInput("IRA rate", scanner)
);
program.calculate();
program.outputResults();
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne, Scanner console) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public void calcIraAmount() {
iraTotal = grossPay * (iraRate / 100.0);
} // End iraAmount
public void calcSavingsAmount() {
saveAmount = grossPay * (saveRate / 100.0);
} // End savingsAmount
public void outputResults() {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of \$" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be \$" + formatCash.format(saveAmount)
+ ", with a investment amount of \$" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of \$" +
+ totalSave + ". Way to go for paying yourself!" );
} // End outputResults
} //End Class
I have a Java program that is designed to take an input of customers, then run a loop for each. Then the user has 3 choices to input: clowns, safari sam, or music caravan. I just don't understand what is wrong with my if statements. You see, if a user enters "clowns", the corresponding if statement works fine and the if statement is executed. However, if a user inputs "safari sam" or "music caravan", the if statements do not execute.
My question is: If the first if statement is executed, then why are the other 2 being skipped (not executing when conditions are met)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
You need to use nextLine() instead of next() to read user input. nextLine() will read the entire line, but next() will only read the next word.
For reading String provided by the user in console you have to use .nextLine()
So try by using this -
String service_type = new_scan.nextLine();
This should store the value of whatever you are providing in the console to the String "service_type".
sorry guys this is my first week at programming and my task is to design a program that calculates regular pay and overtime pay based on user input, but when I put 5.5 in hours or rates it gives me errors I don't really understand why
if there is way to fix the error then how do you get rid of .0 at the end of output integers? thanks a bunch, teacher just assumed we know all the stuff when I took AP CS, this is the review from last years "intro class" so I'm bit overwhelmed, if still have some time left, can you please explain the mechanism behind "double"? to my understanding so far it means you can use decimals as opposed to int where you can only put integers code here
`
import javax.swing.JOptionPane;
public class Salary
{
public static void main(String[] args)
{
String s1, s2;
double number1, number2;
s1=JOptionPane.showInputDialog("Enter the number of hours worked");
s2=JOptionPane.showInputDialog("Enter the rates per hour");
number1 = Integer.parseInt ( s1);
number2 = Integer.parseInt ( s2);
double elseregularp = ( 40*number2);
double regularp = ( number1*number2);
double othours = (number1-40);
double othourspay = ( number2* 15/10.0);
if( number1 <= 40)
{
System.out.println("YOU WORKED "+number1+" HOURS" );
System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
}
else
{
System.out.println("YOU WORKED " + number1+" HOURS");
System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
}
}
}
`
integer.parseInt(...) is accepting a string value which is not the correct input for it. So change it to parseDouble so that it works correctly.
Your final code after modification.
integer.parseInt (...) is changed to Double.parseDouble(...)
import javax.swing.JOptionPane;
public class Salary
{
public static void main(String[] args)
{
String s1, s2;
double number1, number2;
s1=JOptionPane.showInputDialog("Enter the number of hours worked");
s2=JOptionPane.showInputDialog("Enter the rates per hour");
// number1 = Integer.parseInt ( s1);
// number2 = Integer.parseInt ( s2);
number1=Double.parseDouble(s1);
number2=Double.parseDouble(s2);
double elseregularp = ( 40*number2);
double regularp = ( number1*number2);
double othours = (number1-40);
double othourspay = ( number2* 15/10.0);
if( number1 <= 40)
{
System.out.println("YOU WORKED "+number1+" HOURS" );
System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
}
else
{
System.out.println("YOU WORKED " + number1+" HOURS");
System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
}
}
}
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
percentRaise = .04;
raise = (.04 * currentSalary);
else if (rating.equals("Poor"))
percentRaise = .015;
raise = (.015 * currentSalary);
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}
if i add { and } where the whitespace is then it says raise is not initialized. No matter what i do i cant seem to figure out to get it running. Right now it tells me to delete the else to let it run but if i do no matter i write excellent, good, or poor. It does .015 * salary so i cant get excellent or good to run.
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Won't compile because Java sees this as...
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Meaning that the compiler will complain about the else-if without a if statement.
The other problem you're having (when you place { } around the statements) is because Java makes no determination about what the initial value of a local variable will have.
This means Java simply doesn't know what to do with newSalary = currentSalary + raise; as there is no guarantee that raise will have a value assigned to it.
You could overcome this by adding an else condition to the end of your if-else block or simply supplying an initial value to your local variables...
double currentSalary = 0; // employee's current salary
double raise = 0; // amount of the raise
double percentRaise = 0; // percentage of the raise
double newSalary = 0; // new salary for the employee
String rating = ""; // performance rating
And while it might seem annoying, it's better then getting some completely random value which you would have to spend time trying to debug ;)
Updated
Remember, String#equals is case sensitive, this means "Excellent" is not equal to "excellent".
You could use String#equalsIgnoreCase instead
You need to wrap if statements into these things ---> "{}"
so its like this:
if(statement){
//then do someting
}else{
//then do something else
}
You can only write if statements without braces if it contains only one command, if you have more than one command (more than one line) you need to enclose those commands in braces
You have to make sure that if your if statement contains more than one line of code, it is wrapped in braces.
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
{
percentRaise = .06;
raise = (.06 * currentSalary);
}
else if (rating.equals("Good"))
{
percentRaise = .04;
raise = (.04 * currentSalary);
}
else if (rating.equals("Poor"))
{
percentRaise = .015;
raise = (.015 * currentSalary);
}
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}
I'm in a programming class in high-school, and I was given an assignment to make a basic subtotal and top calculator, but I work at a restaurant, so it seemed a little pointless to make a calculator that only let you read in one food. So I tried to make it able to take in multiple food items and add them to one price variable. Sorry if some of this code may seem inefficient or redundant. It's only high-school of course.
The issue is, when I run it, it gets up to the asking if there was another food item the user would like to add, and when I type in "Yes" or "No", the program does nothing. Keeps running, but goes no further. Any explanations?
import java.text.NumberFormat;
import java.util.Scanner;
public class Price {
/**
* #param args
*/
public static void main(String[] args) {
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}
}
You have an infinite loop here:
while (done.equalsIgnoreCase("Yes"));
Once you enter Yes, it will keep sitting there and doing nothing because the value of done is Yes and never changes.
Also your loop structure is a bit odd. Your outer for loop runs as many times as the quantity of the first item. But shouldn't you only be multiplying that number to the cost? Because you are either running the loop for as long as the number of items the user entered (by asking them up front) or you don't ask them the total number of items and simply ask them to enter Yes if they want to add more items; you can't really do both.
Your loop should probably look something like this:
String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();
System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();
//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total
System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}
you need to exit for loop when user enters yes, so you can use label here like below:
outerloop:
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes")){
break outerloop;
}
}
Your current code does not do anything inside the while loop if you don't enter yes. And if you enter yes it will be stuck in infinite loop because of your while loop. This is not the efficeint way of looping, but this code will have least change in your current code.
You're while loop is doing nothing, you had given it a condition, but it has no instruction.
Try something like this..(sorry for my rusty java)
'public static void main(String[] args) {
//variable declaration
bool running = true
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
while(running = true){
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
if(done.equalsIgnoreCase("No")){
running = false
//Allows you to break out of the while loop if the user does not want to add anything else
//DO NOT USE BREAK STATMENTS, IT IS A POOR PROGRAMMING PRACTICE.
};//end if
}//end for
}//end while
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
//You should comment whats going on here
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
//Output
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}//end main