/* My goal is to use the terminal to receive 2 integers and add them together in a Java program. I need to confirm that both terminal entries are ints. If the are, I should proceed to add the ints together. If not, I should print out "Invalid input entered. Terminating..."
I am trying to use an if statement with hasNextInt(), but my program is only verifying the first Scanner input. How do I confirm both Scanner inputs are ints? Any help would be appreciated.
Here is my Java code: */
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 operationInput = input.next().toLowerCase();
switch (operationInput){
case "add":// for addition
System.out.print("Enter two integers:");
if (input.hasNextInt() == false) { //confirm the numbers are integers, otherwise terminate
System.out.println("Invalid input entered. Terminating...");
break;
}
else {
int a1 = input.nextInt();
int a2 = input.nextInt();
int at = a1 a2;
System.out.println("Answer: " at);
input.close();
break;
}
CodePudding user response:
Well, you could change the structure. Instead of the if ( ! input.hasNextInt())
and else
block, you could use a try
block and catch
the exceptions input.nextint()
will throw if there are not two integers. Scanner API # nextInt
System.out.print("Enter two integers:");
try {
int a1 = input.nextInt();
int a2 = input.nextInt();
System.out.println("Answer: " (a1 a2));
}
catch (InputMismatchException ex) {
System.out.println("Invalid input entered. Terminating...");
System.exit (100); }
catch (NoSuchElementException ex) {
System.out.println("Missing input. Expected two integers."
" Terminating...");
System.exit (100); }
finally {
input.close();
}
CodePudding user response:
You already read the int if it's available and basically, you'll just have to repeat this step. You can use an additional flag to indicate whether the program was able to read the two ints successfully:
int a1, a2;
boolean gotTwoInts = false;
if (input.hasNextInt()) {
a1 = input.nextInt();
}
if (input.hasNextInt()) {
a2 = input.nextInt();
gotTwoInts = true;
}
if (!gotTwoInts) {
System.out.println("Invalid input entered. Terminating... ");
break;
}
Update
Complete example:
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 operationInput = input.next().toLowerCase();
switch (operationInput){
case "add": { // curly braces because local variables are block scoped.
System.out.print("Enter two integers:");
int a1 = -1, a2 = -1; // local variables need to be initialized
boolean gotTwoInts = false;
if (input.hasNextInt()) {
a1 = input.nextInt();
}
if (input.hasNextInt()) {
a2 = input.nextInt();
gotTwoInts = true;
}
if (!gotTwoInts) {
System.out.println("Invalid input entered. Terminating... ");
break;
}
System.out.println("Answer: " (a1 a2));
}
}
}
}
CodePudding user response:
I would use method nextLine – rather than method nextInt
and have the user enter the two integers on a single line, separated by a space.
Also, I think it is a good idea to divide the code into methods and not to write all the code in method main
.
It appears that you intend to also add subtract, multiply and divide operations, hence part of the below code can be considered as a template to help you complete your program.
import java.util.Scanner;
public class Calculator {
private static final int NUMBER_OF_OPERANDS = 2;
private static Scanner input = new Scanner(System.in);
private static int[] operands = new int[NUMBER_OF_OPERANDS];
private static int add() {
getOperands();
return operands[0] operands[1];
}
private static void getOperands() {
System.out.print("Enter two integers separated by space: ");
String value = input.nextLine();
String[] parts = value.split("\\s ");
if (parts.length < NUMBER_OF_OPERANDS) {
throw new RuntimeException("Less than two integers entered.");
}
operands[0] = Integer.parseInt(parts[0]);
operands[1] = Integer.parseInt(parts[1]);
}
public static void main(String[] args) {
System.out.println("List of operations: add subtract multiply divide alphabetize");
System.out.print("Enter an operation: ");
String operationInput = input.nextLine().toLowerCase();
int result = 0;
switch (operationInput) {
case "add":// for addition
result = add();
break;
case "subtract":
break;
case "multiply":
break;
case "divide":
break;
case "alphabetize":
break;
default:
System.out.println("Invalid operation: " operationInput);
System.exit(1);
}
System.out.println("Result: " result);
}
}
Note that RuntimeException
is an unchecked exception and that [static] method parseInt
– of class java.lang.Integer
– may throw NumberFormatException
which is also an unchecked exception.