1

The code here worked until I needed to ensure the user didn't cause an exception by entering a string instead of an integer or double. I basically need to make sure the user enters enough to be greater than or equal to the price, so that the program can return the correct amount of change.

public static double findChange()
{
    System.out.println("\nPlease insert: " + price + " (enter payment amount)");

        while (payment < price)
        {
            try {
                payment = kb.nextDouble();
                //takes input until user has entered the needed amount

            } catch (Exception e) 
            {
                System.out.println("Error: Please enter valid currency");
            }
            price = price - payment;
            price = (price * 100) / 100;
            System.out.println("Please insert:" + price);
            if (payment <= price)
                stringError = false;
        }
    } 

    change = payment - price;
    change = Math.round(change * 100);
    change = change / 100;
    System.out.println("\nChange Given: $" + change);
    //determines amount of change to give user and formats to cents

    return change;

}
  • 2
    Don't catch `Exception`: catch a more specific exception type. – Andy Turner Dec 03 '15 at 15:01
  • 1
    @brso05 Not quite. `Exception` (even precise ones) shouldn't be part of standard control flow logic, they should be used to handle exceptional cases. Scanner introduced `hasNext...` kind of methods precisely to avoid using exceptions. – Pshemo Dec 03 '15 at 15:23
  • @brso05 Creating exception is expensive operation so if there are other ways to prevent them we should use them. `Scanner#hasNext...` is canonical example of such situation. – Pshemo Dec 03 '15 at 15:42
  • @brso05 OK, TIL that `Scanner#hasNextDouble` internally is using try-catch to test type of data which means that there will be no performance gain here so this method is no longer good example of what I try to say (damn you Scanner, but I still hope it will be improved someday). But rule says the same: if we can avoid creating exception (which is expensive operation) we should do so and use other less expensive (and probably more readable) code. – Pshemo Dec 03 '15 at 16:21

3 Answers3

1

Change

catch (Exception e) 
{
    System.out.println("Error: Please enter valid currency");
}

to

catch (Exception e)
{
    System.out.println("Error: Please enter valid currency");
    continue;
}

This way, if the user inputs a non double value, the error message will be shown and he will be asked to re-enter a value (The continue; instruction skips the current iteration & passes on to the next one).

Mohammed Aouf Zouag
  • 16,366
  • 3
  • 36
  • 64
0
 try {
                payment = kb.nextDouble();
                //takes input until user has entered the needed amount

            } catch (Exception e) 
            {
                System.out.println("Error: Please enter valid currency");
            }
            price = price - payment;

When an exception occurs, this will cause troubles, since payment has no value (or not the right one).

put your catch statement later in the while block

Stultuske
  • 8,465
  • 1
  • 19
  • 30
0

Try the following:

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            findChanges();
        }

        private static double findChanges()
        {
            string xPrice;
            string xPayment;
            double price = 0d;
            double payment = 0d;
            double change = 0d;
            Console.WriteLine("Please insert price and payment amout");
            Console.WriteLine("Price ?");
            xPrice = Console.ReadLine();
            bool PriceIsNumber = double.TryParse(xPrice, out price);
            Console.WriteLine("Payment ?");
            xPayment = Console.ReadLine();
            bool PaymentIsNumber = double.TryParse(xPayment, out payment);

            if (PriceIsNumber == true && PaymentIsNumber == true)
            {
                if (payment > price)
                {
                    try
                    {
                        // price = price - payment;
                        // price = (price * 100) / 100;
                        change = payment - price;
                        // change = Math.Round(change * 100);
                        // change = change / 100;
                        Console.WriteLine("Change = " + change.ToString());
                    }
                    catch (Exception e)
                    {
                        // supress or process e
                    }
                }
            }
            else
            {
                Console.WriteLine("Please enter valid currency");
            }
            Console.Read();
            return change;
        }
    }
}
Ashraf Sada
  • 3,511
  • 1
  • 36
  • 43