ok so I have a program that involves if and else statements. in the program ther
ID: 673829 • Letter: O
Question
ok so I have a program that involves if and else statements. in the program there is a scanner object and when program is ran it asks the user for two integers (represented as operand in program and operand2 in program) the program divides multiplies and uses mod on these two ints. so if I were to enter x for the first int instead of an int I would get an error. so first statement in code is System.out.print("Enter an integer: "); followed by operand = keyboard.nextInt(); How would I use an if else statement around the first read statement that uses the scanner objects hasNextInt() method. so If the condition is true, it reads the value using the normal code nextInt() method. If the condition is false, it read the value using the nextLine() method and print the error message "Bad value: " + badValue.
Explanation / Answer
Solution :
package com.chegg.nancy.solution;
import java.util.Scanner;
public class Enter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
while (true) {
boolean isValid = checkVal(sc);
if (isValid) {
sc.nextLine();
// do your stuff here.
}
}
} catch (Exception e) {
System.out.println("bad Input");
} finally {
sc.close();
System.out.println("Program exited!");
}
}
private static boolean checkVal(Scanner sc) throws Exception {
if (!sc.hasNextInt())
throw new Exception();
else
return true;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.