Akmar275 Akmar275 - 2 months ago 7
Java Question

Java While Loop breaking with a negative

I am having a problem with this java project I am working on for tomorrow. I am supposed to make a while loop that prompts the user for the prices of items and end the loop with any negative number, that negative number cannot be counted. Then I have to prompt the user for their membership discount level plat 15% off/gold 7%/silver 3%/non member 0% off using variables 3,2,1,0 respectively. For invalid input of status of membership, the user needs to enter again with a valid one using a do-while loop. Then I use the appropriate discount % off the sum of the items then tax it. The last few steps are simple enough, but I am stuck at the loops.

I did some searching and found this block of code on this site that does the job for the first while loop but does not end in the way I need it to.
Using While Loop instead of a For Loop in Java to ask User Input

I modified it to fit my needs but I still cannot find a way to make the throwable = to any negative number ie <0. Is that even possible? I am pretty sure there is a way to do this much simpler without try/catch which I have not learned yet. Here is my very slightly modified version

Scanner askPrice = new Scanner(System.in);
BigDecimal totalPrice = new BigDecimal("0");
Scanner keyboard = new Scanner(System.in);
while (true) {
System.out.println("Enter item price or negative number to quit:") ;
try {
double price = askPrice.nextDouble();
totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));
}
catch (Throwable t) {
break;
}
System.out.println(totalPrice.toString());
}


I tried turning the try and catch statements into if / else and replacing the catch throwable with else(askPrice <0), but I was getting tons of errors.

I greatly appreciate any help that can be offered.
Thanks.

Answer

This sounds like homework. I know a lot of teachers are against students using 'break' to exit a loop. Here is how I would do it. A try-catch statement is unnecessary.

public static void main(String[]args) {

Scanner keyboard = new Scanner(System.in);
    double input = 0.0;
    double totalPrice = 0.0;

    do {
        totalPrice += input;
        input = keyboard.nextDouble();
    }

    while(input >= 0);
}

Using a while loop:

public static void main(String[]args) {

Scanner keyboard = new Scanner(System.in);
    double totalPrice = 0.0;
    double input = keyboard.nextDouble();

    while(input >= 0) {
    totalPrice += input;
    input = keyboard.nextDouble();
    }
}