Reputation: 664
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.
Upvotes: 3
Views: 909
Reputation: 1786
Use Integer.parseInt(input.nextLine())
in a try-catch block that looks for a NumberFormatException
.
If you really must avoid the use of try-catch, then your idea of calling input.hasNextInt()
before attempting to parse the integer with input.nextInt()
will work.
int userInt = 0;
if (input.hasNextInt()) {
userInt = input.nextInt();
} else {
System.out.println("That wasn't a valid int.");
// Take whatever corrective action you want here.
}
If you have a UI for the calculator, then you can ensure that clicking specific buttons only sends valid values back to the calculation backend. However, since it looks like you are letting your users type in their values on the command line, there isn't a way to lock their keyboard into only being able to type valid numbers. As a result you have to test the validity of their input on your own.
Also, when I'm trying to get a number from a user, I like to loop and keep asking them for a valid number instead of terminating the program. Consider something like this.
Scanner input = new Scanner(System.in);
int userInt = 0;
boolean userIntReceived = false;
while (!userIntReceived) {
try {
userInt = Integer.parseInt(input.nextLine());
userIntReceived = true;
} catch (NumberFormatException e) {
System.out.println("That wasn't a valid int. Please try again.")
}
}
// Now you have a valid int from the user.
input.close();
Upvotes: 6