The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Apr 2017 |
| Last Sign in: | 103 Weeks Ago, 2 Days Ago |
| Questions Answered: | 4870 |
| Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
I need to modify the Continue? (y/n): code so when a user enters two or more values the application will still work correctly. Meaning it should work even if the user makes tow or more entries for a single prompt. I believe I need to validate the input, display an error message until either Y, y, N, or n is entered and discard any extra entries.
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
Â
public class InvoiceApp
{
Â
public static String getValidCustomerType(Scanner sc)
{
String customerType="";
while(true)
{
System.out.print("Enter customer type (r/c): ");
customerType= sc.next();
if(customerType.equalsIgnoreCase("c") ||customerType.equalsIgnoreCase("r"))
break;
Â
else
System.out.println("invalid code,");
}
Â
return customerType;
Â
}
Â
Â
public static double getValidSubtotal (Scanner sc)
{
double ;
String garbagedata;
while(true)
{
System.out.print("Enter subtotal: ");
if( sc.hasNextDouble())
{
.nextDouble();
if(subTotal>0 && subTotal<1000)
break;
}
else
{
.next();
Â
}
Â
System.out.println("invalid subTotal, please enter a double value greater than 0 and less than 1000");
}
Â
return subTotal;
Â
Â
Â
}
Â
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
double discountPercent = 0;
double ;
Â
Â
while (choice.charAt(0)=|| choice.charAt(0)=)
{
try
{
// get the input from the user
String customerType (sc);
Â
(sc);
// get the discount percent
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;
}
}
{
catch(InputMismatchException e)
}
// 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();
}
}
}