I have been creating a simple calculator for a homework assignment, but I may have used a technique more advanced than what we have been taught.
Here is my implementation, which uses try/catch to handle exceptions.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("List of operations: add subtract multiply divide alphabetize");
System.out.println("Enter an operation:");
String selection = input.next();
selection = selection.toLowerCase();
switch (selection) {
case "add":
int sum = 0;
try {
int integerOne = input.nextInt();
int integerTwo = input.nextInt();
sum = integerOne + integerTwo;
}
catch (Exception e) {
System.out.println("Invalid input entered. Terminating...");
break;
}
System.out.println("Answer: " + sum);
break;
I've left out the rest of the code as it is very similar, just for different operations.
How can I prevent my users from inputting a double or string and getting an InputMismatchException without utilizing try/catch? I also cannot use var type inference. I have been trying to find a way to possibly use the hasNextInt() method or something, but as far as I can tell I will run into the same problem.
Do I have to use nextLine() instead and parse the string passed as input for integers?
Thanks in advance for the help.