-Im trying to understand try catch statements.. -with the user enters a string i
ID: 3760443 • Letter: #
Question
-Im trying to understand try catch statements..
-with the user enters a string instead of an int i want the program to cath the (InputMismatchException e) and print out " this is not correct.
-Im including my code that is not working, please help I dont want the compiler to print out the red inputMismatch .. instead what i said before the "this is not correct:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args)
{
int digit = numberFromUser();
int result = sevenModulusN(digit);
System.out.printf("7 %% %d = %d", digit, result);//illegalFormatConversion
}
private static int numberFromUser()
{
Scanner input = new Scanner(System.in);
try{
System.out.print("number: ");
return input.nextInt();
}catch(InputMismatchException e)
{
System.out.println("This is not correct");
}
return input.nextInt();
}
private static int sevenModulusN(int number)
{
return 7 % number;
}
}
Explanation / Answer
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args){
int digit = numberFromUser();
if (digit != -1) {
int result = sevenModulusN(digit);
System.out.printf("7 %% %d = %d", digit, result);
}
}
private static int numberFromUser(){
Scanner input = new Scanner(System.in);
int in = -1;
try {
System.out.print("number: ");
in = input.nextInt();
} catch (Exception e) {
System.out.println("This is not correct");
}
return in;
}
private static int sevenModulusN(int number) {
return 7 % number;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.