I am running into an issue with my Java code and I know where the issue lies, but I can't seem to figure out what I need to do to correct it. Can someone please help? This is the line that is causing the issue and I'm not sure how to fix it. subtotal = sc.nextDouble();
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InvoiceApp
{
private static double subtotal;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
String customerType = getValidCustomerType(sc);
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again. \n");
continue;
}
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}
// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (!customerType.equalsIgnoreCase("r") && !customerType.equalsIgnoreCase("c"))
{
System.out.println("Invalid customer type. Try again. \n");
}
else
{
isValid = true;
}
sc.nextLine();
}
return customerType;
}
}
Program does not hang when it executes:
subtotal = sc.nextDouble();
rather it simply waits for a double value input from the console. Input a value, and the rest of your program magic should follow.
The issue is that you have an extra call that scans the subtotal there.
One in the try-catch block
try
{
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
and then another one right before you calculate the discountPercent
// get the discount percent
double discountPercent = 0.0;
double subtotal = sc.nextDouble();
This is what's making you enter the amount twice. Just remove the second call and the program should run fine.
Related
I have a java program that calculates users' income taxes, with some help the project now runs correctly, but I am supposed to add an option for the user to process additional customers once they have finished with a customer by entering 'y' into a prompt. I need the prompt to say: "Process another customer? (y/n)?" Since the user could also hit "n" this prompt will also have to have a command for both 'y' and 'n' how and where do I do this and where do I need to put the prompt in my code? here is my code:
import java.util.Scanner;
public class TaxCalculator {
public static void main(String[] args) {
final double RATE1 = 0.20;
final double RATE2 = 0.25;
final double RATE3 = 0.10;
final double RATE4 = 0.15;
final double RATE5 = 0.30;
final double RATE1_SINGLE_LIMIT = 0;
final double RATE2_MARRIED_LIMIT = 0;
final double RATE3_COHABITATING_LIMIT = 20000;
final double RATE4_COHABITATING_LIMIT = 50000;
double tax = 0;
//Enter Income
Scanner in = new Scanner(System.in);
System.out.print("Please enter your income: ");
double income = in.nextDouble();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
//Calculate Taxes
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
}else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
}else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
}else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax= RATE5 * income;
}
System.out.print("Your tax is: " + tax);
}
}
Make use of a do...while loop.
The while and do-while Statements | Java Documentation
import java.util.Scanner;
public class TaxCalculator {
static void calculate() {
final double RATE1 = 0.20;
final double RATE2 = 0.25;
final double RATE3 = 0.10;
final double RATE4 = 0.15;
final double RATE5 = 0.30;
final double RATE1_SINGLE_LIMIT = 0;
final double RATE2_MARRIED_LIMIT = 0;
final double RATE3_COHABITATING_LIMIT = 20000;
final double RATE4_COHABITATING_LIMIT = 50000;
double tax = 0;
Scanner in = new Scanner(System.in);
//Enter Income
System.out.print("Please enter your income: ");
double income = in.nextDouble();
in.nextLine();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
in.nextLine();
//Calculate Taxes
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
} else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
} else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
} else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax = RATE5 * income;
}
System.out.print("Your tax is: " + tax);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String newResponse = "";
do {
calculate();
System.out.println();
System.out.println("Process another response?. Please enter 'y' for yes, or 'n' for no: ");
newResponse = in.next();
in.nextLine();
} while (newResponse.equals("y"));
}
}
You can do this in the end of your program, after you display the tax of the first user you can ask if there is a new user or no, if yes you will repeat the same steps as for the first user and if no your program will finish, to do that you must first add a boolean variable (or integer as you want), to know if there is a new user or no:
boolean newCustomer = false;
then your entire code will be inside a do while loop as following:
do{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your income: ");
double income = in.nextDouble();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
//Calculate Taxes
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
}else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
}else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
}else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax= RATE5 * income;
}
System.out.println("Your tax is: " + tax);
System.out.print("Please type 'y' for a new customer, or 'n' to finish the program : ");
String customer = in.next();
if(customer.equals("y"))
newCustomer = true;
else
newCustomer = false;
}
while(newCustomer);
I have this code that creates invoice amounts. I am trying to make it so I can have a Y/N (Yes or No) question in order to continue, however, if I give it anything other than a 'Y' it quits. I want it to only accept 'Y' and 'N' as answers.
and if answered 'N' still prints string 'message'.
import java.util.Scanner;
public class InvoiceApp {
public static void main(String[] args) {
// welcome the user to the program
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform invoice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
if (choice.equalsIgnoreCase("n")) { // trying to make a Y/N question
}
// get the invoice subtotal from the user
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
// calculate the discount amount and total
double discountPercent = 0;
if (subtotal <= 100) {
discountPercent = .1;
} else if (subtotal <= 200) {
discountPercent = .2;
} else if (subtotal >= 500) {
discountPercent = 0.25;
}
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Thanks for any help.
You can do this:
while (true){
if(choice.equalsIgnoreCase("y"){
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
// calculate the discount amount and total
double discountPercent = 0;
if (subtotal <= 100) {
discountPercent = .1;
} else if (subtotal <= 200) {
discountPercent = .2;
} else if (subtotal >= 500) {
discountPercent = 0.25;
}
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
else if(choice.equalsIgnoreCase("n")){
//....
break;
}
else{
System.out.print("Please enter (y/n): ");
choice = sc.next();
System.out.println();
}
}
OR:
while (!choice.equalsIgnoreCase("n"){
if(choice.equalsIgnoreCase("y"){
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
// calculate the discount amount and total
double discountPercent = 0;
if (subtotal <= 100) {
discountPercent = .1;
} else if (subtotal <= 200) {
discountPercent = .2;
} else if (subtotal >= 500) {
discountPercent = 0.25;
}
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
else{
System.out.print("Please enter (y/n): ");
choice = sc.next();
System.out.println();
}
}
How would I make it to where I wanted my code to loop if any character besides n or N was entered? So if the user inputs a, t, w, g, etc., it would return back to the beginning of the current loop. I'm usin an if/else if loop. (Just messing around with NetBeans).
import java.util.Scanner;
public class InvoiceApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform invoice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
if (choice.equalsIgnoreCase("y"))
{
// get the invoice subtotal from the user
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
// calculate the discount amount and total
double discountPercent= 0.0;
if (subtotal >= 200)
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .1;
else
discountPercent = 0.0;
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
else if (choice.equalsIgnoreCase("n"));
}
}
}
Use a while(!(choice.equalsIgnoreCase("n"))) instead of your current if statement. You won't need an else section.
I am trying to write a ' try and catch ' method in this example, but for some reason I'm getting in error on all of my variables saying; "cannot find symbol". This is happening in all instances of:
subtotal &
customerType. Does anyone know what can be causing this?
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.*;
public class InvoiceApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
try
{
//System.out.print("Enter customer type (r/c): ");
String customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
// get the discount percent
double discountPercent = 0;
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
{
discountPercent = .1;
}
// calculate the discount amount and total
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println(
"Discount percent: " + percent.format(discountPercent) + "\n" +
"Discount amount: " + currency.format(discountAmount) + "\n" +
"Total: " + currency.format(total) + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
The problem with your code is the scope of your variables: if you declare something in a try block, it is visible only within that try block; it is not going to be visible outside the try block, including even the catch blocks after it.
In order to get around this problem, declare the variable outside the try block:
String customerType;
double subtotal;
try {
//System.out.print("Enter customer type (r/c): ");
customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
} catch (InputMismatchException e) {
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
You declare subtotal and customerType in try block, so that variable only visible in try block.
Change your code like this will fix the problem:
double subtotal = 0;
String customerType = "";
try
{
//System.out.print("Enter customer type (r/c): ");
String customerType = getValidCustomerType(sc);
System.out.print("Enter subtotal: ");
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next();
System.out.println("Error! Invalid number. Try again \n");
continue;
}
More : Blocks and Statements
You declared subtotal and customertype inside the brackets of the try {}. That is the only place where they are valid. If you declared them before the try this would have been fine.
private static String getValidCustomerType(Scanner sc)
{
String customerType = "";
boolean isValid = false;
while (isValid == false)
{
System.out.print("Enter customer type (r/c): ");
customerType = sc.next();
if (customerType.equalsIgnoreCase("r") || (customerType.equalsIgnoreCase("c")))
isValid = true;
else
{
System.out.println("Invalid customer type. Try again. \n");
}
sc.nextLine();
}
return customerType;
}
}
I can't get the while loop to work. The Program prompt user whether (s)he wants to continue, enter 0 toquit or any other integer to continue. If the user wants to c
ontinue, the program will loop back to themenu, otherwise, it will exit. Thus, you should have a sentinel-controlled loop that will end when a 0 is entered
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
while(gender != 0);//begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if(gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if(gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if(gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
}
}
}
This line is responsible:
while(gender != 0);//begin sentinel controlled while loop
Look closely. There is a semi-colon at the end - that is the entire statement. The {} block that follows does not belong to the loop (and is executed exactly once).
Try dropping the ; from the end - we've fixed our while loop, but now the {} loop body doesn't execute at all. This is because gender is initialized with a value of 0. So to get our loop to execute at least once we need to either initialize gender to something else, or use a do-while loop.
Here is the modified code using a do-while.
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
do //begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if (gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if (gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if (gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
} while(gender != 0); //end sentinel controlled while loop
}
}
Try this:
while(gender != 0);//<-- remove the semi colon,loop gets terminated by it
Also declare gender as:
int gender = -1;//<-- this will cause the loop to start