Error handling is one of the most important topics we will learn. By catching errors we can allow the system to return from a failed state. If we neglect to properly handle errors the system will be vulnerable both from users and nefarious actors who may intentionally try to get our program to fail. It is important to carefully identify weak points in our software and mitigate any problematic areas.
In the last lesson we learned about getting user input. In this lesson we will utilize try/catch blocks and if statements to catch errors. It is important to note that an if statement will run every iteration, but a try/catch exception taxes the system much more. A good rule of thumb when deciding which to use is “exceptions should be exceptional”, if we don’t think the error will happen often utilize and exception. Otherwise try to catch the error another way.
In this application we are asking the user how many prices they want to input and then we will collect each of the prices they provide. By placing these inputs within a while loop we can utilize continue to go back to the top of the iteration if an error occurs. If the first loop completes successfully without errors we break from the loop.
In the second loop we utilize a similar technique, however in this loops we have to iterate through the loop based on the amount of times the user originally specified (amount). There are several ways to accomplish this. I chose to create a counter, when the counter equals the amount it will break from the loop.
To store the prices I instantiate an array with the length the same as the amount the user originally specified.
We then iterate through the array to print the prices to console. you may notice that I utilize a printf instead of a println. When we want to format the string of an output we can use printf. The % sign signifies the beginning for the formatted value. The formatting %,.2f will give us a coma in the thousands position and two decimal points, it will format the output to look like currency!
We’ve learned how to handle exceptions, and dove into loops. All though loops are fast, it is considered best practice to utilize recursion instead of iteration. The reason is we can reuse the functionality when utilizing recursion which can decrease the amount of code, it is also much easier to read and understand. This doesn’t mean we should never use loops, they are an important part of programming. As the lessons gradually get more difficult you will start to learn how to use loops effectively.
import java.util.Scanner;
public class SellItems {
int amount;
int counter;
double price;
double[] prices;
public void priceInput() {
Scanner input = new Scanner(System.in);
while (true) {
try {
System.out.println("How many prices will you be entering? ");
amount = input.nextInt();
if (amount < 1) {
System.out.println("You must have one or more price(s). \n");
continue;
}
} catch (Exception InputError) {
System.out.println("Input Error: Please input a number. \n");
input = new Scanner(System.in);
continue;
}
break;
}
//initalizes the prices list
prices = new double[amount];
counter = 1;
while (true) {
try {
System.out.println("Enter price " + (counter) + ": ");
price = input.nextDouble();
if (price < 0) {
System.out.println("Value Error: An item can not have a negative price. \n");
continue;
} else if (counter == (amount)) {
prices[counter - 1] = price;
break;
}
} catch (Exception InputError) {
System.out.println("Input Error: Please input a number. \n");
input = new Scanner(System.in);
continue;
}
prices[counter - 1] = price;
counter++;
}
input.close();
priceOutput();
}
public void priceOutput() {
System.out.println("\n"+"The Prices are: ");
for(counter = 0; counter < amount; counter++) {
System.out.printf("$%,.2f \n",prices[counter]);
}
}
public static void main(String[] args) {
SellItems Items = new SellItems();
Items.priceInput();
}
}