Quick easy Java question.
I'm in a beginning Java class and am running into an issue right off the bat.
I need to modify this so that the program ends only when "n" or "N" is entered. I've been using the not operator, but I'm either using it incorrectly, or I'm using it in the wrong place.
Here is the code for the application:
Code Java:
import java.util.Scanner;
public class InvoiceApp
{
public static void main(String[] args)
{
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) //This is where I've been entering the not operator as (!choice.equalsIgnoreCase("n")), but when doing so, the program compiles without everything that follows (below), which leads me to believe I'm putting it in the wrong place.
{
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();
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;
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println(); // Should the not operator go here?
}
}
}
Re: Quick easy Java question.
When I run the code you have, replacing the equalsIgnoreCase with what you have commented out on the same line, it runs as expected.
Re: Quick easy Java question.
I have compiled your code and it almost works.
When you first run it, if you type N straight away, an exception is thrown. This is because the scanner is looking for a double value. It works ok if you enter a double value. When you are prompted to press y/n to continue at the end of the program, this function works fine and the program exits when N is entered.
Are you looking to be able to exit this program with N on the very first prompt?