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.
Related
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();
}
}
Hi I needed help with doing a calculation in this right here. On the line where it has single, i want to add the number to the calculation but it just adds it as if im just writing the number itself in a sentence. How do i add it as if its a calculation, im very stuck and need help. (Its the last line of code). I also wanted to know how i can limit the amount of letters a user can input, since i only want them to either enter 's' or 'm'. How can i limit them to only these two so they dont use a letter like 'g' for example, since that wont work.
import java.util.Scanner;
public class FedTaxRate
{
public static void main(String[] args)
{
String maritalStatus;
double income;
int single = 32000;
int married = 64000;
Scanner status = new Scanner(System.in);
System.out.println ("Please enter your marital status: ");
maritalStatus = status.next();
Scanner amount = new Scanner(System.in);
System.out.print ("Please enter your income: ");
income = amount.nextDouble();
if (maritalStatus.equals("s") && income <= 32000 )
{
System.out.println ("The tax is " + income * 0.10 + ".");
}
else if (maritalStatus.equals("s") && income > 32000)
{
System.out.println ("The tax is " + (income - 32000) * 0.25 + single + ".");
}
}
}
To answer your second question about limiting the input, you can try using a switch case statement. The default allows you to write code for the case when maritalStatus is not equal to either "s" or "m". You can also create a do-while loop to keep asking for input until maritalStatus is equal to either "s" or "m".
Scanner status = new Scanner(System.in);
String maritalStatus = status.nextLine();
do {
System.out.println("Enter your marital status.")
switch (maritalStatus) {
case "s":
// your code here
break;
case "m":
// your code here
break;
default:
// here you specify what happens when maritalStatus is not "s" or "m"
System.out.println("Try again.");
break;
}
// loop while maritalStatus is not equal to "s" or "m"
} while (!("s".equalsIgnoreCase(maritalStatus)) &&
!("m".equalsIgnoreCase(maritalStatus)));
You only need one Scanner. You can use an else with your income test. I would suggest you calculate the tax once, and then display it with formatted IO. Something like,
public static void main(String[] args) {
int single = 32000;
int married = 64000;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your marital status: ");
String maritalStatus = sc.next();
System.out.print("Please enter your income: ");
double income = sc.nextDouble();
double tax;
if ("s".equalsIgnoreCase(maritalStatus)) {
if (income <= single) {
tax = income * 0.10;
} else {
tax = (income - single) * 0.25 + single;
}
} else {
if (income <= married) {
tax = income * 0.10;
} else {
tax = (income - married) * 0.25 + married;
}
}
System.out.printf("The tax is %.2f.%n", tax);
}
I'm just starting out in java and I'm trying to make my applet only stop when I type "n" or "N". If I type "y or "Y" I want it to run the other code.
Here is the code:
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"))
{
// 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();
}
}
}
if you're trying to implement an applet then you should subclass from Applet... but if you implement an Application (looks like you're doing it so right now) then you can quit your application by simply calling System.exit(0);
your programm will quit also when you simply leave your while(...)-loop, you can do it by calling
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
if("n".equalsIgnoreCase(choice){
break;//this will make you jump out of the while loop
}
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.
I'm trying to make a virtual store program. Synopsis is if at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax.
The problem is that the program would ask user for item and quantity once, then it goes into checkout mode. Whenever I put 'q', it goes to the next line.
Here is the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import java.io.*;
public class virtualStore {
public static void main(String [] args) throws IOException{
/* If the user enters an item number, the program should ask the user to enter how many of that item
they want, and then print the menu again. If at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax. You should use the Math.round() and
System.out.printf methods to round numbers and to display to 2 decimal places. */
Scanner keyboard = new Scanner (System.in);
String input;
char c = ' ';
char q = ' ';
//tax rates
double CAtaxRate = .09;
double NVtaxRate = .07;
double WAtaxRate = .065;
double other = .06;
double tax = 0;
//checkout
double checkout = 0;
double total;
double cash = 0;
double change = 0;
//items
double mushrooms = 0.3;
double onions = 0.6;
double watermelon = 2.5;
double cookies = 1;
int item = 0;
//number of items
int numMushrooms = 0;
int numOnions = 0;
int numWatermelon = 0;
int numCookies = 0;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Alex's Store."
+ " Here is the menu. "
+ "\nEnter the item number to add it to your cart,"
+ " enter \'c\' to checkout or \'q\' to quit. ");
while(true)
//while(c != 'c' && c != 'q')
{
for (item = 1; item < 4; item ++){
System.out.println("Item\t\t\tPrice\t\t\tQuantity");
System.out.println("---------------------------------------------------------");
System.out.println("1. Mushrooms\t\t($0.30/$0.25)\t\t" + numMushrooms);
System.out.println("2. Onions\t\t($0.60/$0.50)\t\t" + numOnions );
System.out.println("3. Watermelon\t\t($2.50/$2.00)\t\t" + numWatermelon);
System.out.println("4. Cookies\t\t($1.00/$0.75)\t\t" + numCookies);
System.out.println("---------------------------------------------------------");
System.out.println("Enter item number between 1 through 4");
System.out.println("or enter 'c' for checkout or 'q' for quit.");
input = keyboard.nextLine();
item = Integer.parseInt(input);
if (input.equals("1"))
{
System.out.println("Enter how many items you want.");
String m = keyboard.nextLine();
numMushrooms = Integer.parseInt(m);
}
else if (input.equals("2"))
{
System.out.println("Enter how many items you want.");
String o = keyboard.nextLine();
numOnions = Integer.parseInt(o);
}
else if (input.equals("3"))
{
System.out.println("Enter how many items you want.");
String w = keyboard.nextLine();
numWatermelon = Integer.parseInt(w);
}
else if(input.equals("4"))
{
System.out.println("Enter how many items you want.");
String co = keyboard.nextLine();
numCookies = Integer.parseInt(co);
}
}
if (numMushrooms > 10)
{
mushrooms = 0.25;
}
else if (numOnions > 10)
{
onions = 0.5;
}
else if (numWatermelon > 10)
{
watermelon = 2;
}
else if (numCookies > 10)
{
cookies = .75;
}
// quit option
String quit = scanner.nextLine();
q = quit.charAt(0);
if (quit.equalsIgnoreCase("q"))
{
System.out.println("Goodbye");
scanner.close();
System.exit(0);
}
// checkout option
String ch = scanner.nextLine();
c = ch.charAt(0);
if (ch.equalsIgnoreCase("c"))
{
//checkout
checkout = numMushrooms * mushrooms + numOnions * onions + numWatermelon * watermelon + numCookies * cookies;
//tax
total = tax * checkout + checkout;
System.out.print("Enter state abbreviations: ");
input = keyboard.nextLine();
PrintWriter outputfile = new PrintWriter("receipt.txt");
outputfile.println("Your cart: ");
outputfile.println("Sub total:$ " + dollar.format(checkout));
if (input.equalsIgnoreCase("CA"))
{
total = CAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + CAtaxRate);
outputfile.println("Tax: $" + dollar.format(CAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("NV"))
{
total = NVtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + NVtaxRate);
outputfile.println("Tax: $" + dollar.format(NVtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("WA"))
{
total = WAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + WAtaxRate);
outputfile.println("Tax: $" + dollar.format(WAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase(input))
{
total = other * checkout + checkout;
outputfile.println("Tax Rate: " + other);
outputfile.println("Tax: $" + dollar.format(other * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
outputfile.println("-----------------------------------------------------");
input = keyboard.nextLine();
cash = Integer.parseInt(input);
outputfile.println("Enter amount of cash: $" + dollar.format(cash));
change = cash - total;
outputfile.println("Change due: $" + dollar.format(change));
outputfile.println("Thank you for shopping at Alex's store!");
outputfile.close();
FileWriter fw = new FileWriter("receipt.text", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("C:\\Desktop\\Receipt.txt ");
pw.close();
}
}
}
}
You're using the wrong model to get user input.
Try doing something that looks like:
while(true) {
// Print the menu messages
String input = scanner.readLine();
if(input.equals("c")) {
// Read in and handle state abbreviation
} else if(input.equals("q")) {
System.exit(0);
} else {
int itemNumber = Integer.parseInt(input);
// Parse and handle item number
}
}