Catching InputMismatchException doesn't return the message - java

So I'm making this school assignment and basically need to make sure that the user inputs a valid option (1, 2 or 3).
I should of used switches but this is what I made:
private void choice() {
try {
Scanner s = new Scanner(System.in);
int option = s.nextInt();
if (option == 1) {
start();
}
if (option == 2) {
info();
}
if (option == 3) {
System.exit(0);
}
throw new InputMismatchException("Enter valid input");
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
}
If you enter a number in the console it will return my message, if you enter anything else it will return "null". Why is that? Because if I remove the exception and look at the stacktrace (when entering a letter for example) it shows an InputMismatchException.
Thanks in advance!

public void choice() throws InputMismatchException {
Scanner s = new Scanner(System.in);
int option = 0;
try {
option = s.nextInt();
} catch (InputMismatchException e) {
throw new InputMismatchException("Enter valid input");
}
if (option == 1) {
System.out.println("e");
} else if (option == 2) {
System.out.println("f");
} else if (option == 3) {
System.exit(0);
} else {
throw new InputMismatchException("Enter valid input");
}
}
public static void main(String[] args) {
try {
new Test().choice();
} catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
}
Put int option, inside the try. Done.

Related

How to loop the program after an exception is thrown

I have the following code that might throw exceptions:
import java.util.*;
import java.io.*;
class Test {
public static void main (String [] args) {
try {
Scanner keyboard = new Scanner (System.in);
int n1, n2;
System.out.print("Type an int: ");
n1 = keyboard.nextInt();
System.out.print("Type another int: ");
n2 = keyboard.nextInt();
int r = n1/n2;
}
catch (ArithmeticException e) {
System.out.println("Divide by 0");
}
catch (InputMismatchException e) {
System.out.println("Wrong entry");
}
}
}
After an exception is thrown. I want the program to go back to asking the user to enter a new int again instead of exiting.
Wrap your code with a while (true) and add a break at the end of the try block, so that it will be reached only if no exceptions are thrown.
e.g.
while (true) {
try {
// your code goes here ....
break; // this will only be reached if no exceptions thrown
}
catch (...) {
}
}; // close the while loop
// this will be reached after the break only, i.e. no exceptions
while (true) {
try {
// your code
break;
}
catch (Exception e) {
}
};
I would use an infinite loop. You can exit it using a break statement when you are ready.
public static void main(String[] args) {
while (true) {
try {
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
int n1, n2;
System.out.print("Type an int: ");
n1 = keyboard.nextInt();
System.out.print("Type another int: ");
n2 = keyboard.nextInt();
int r = n1 / n2;
//Do whatever... use 'break' to exit the loop when you are done
} catch (ArithmeticException e) {
System.out.println("Divide by 0");
} catch (InputMismatchException e) {
System.out.println("Wrong entry");
}
}
}
I don't like the "while (true) with a break" idiom. I find it clearer in this case -- I rarely have rules that apply in all cases -- to introduce an auxiliary variable that controls looping.
boolean repeat;
do {
repeat = false;
try {
...stuff...
}
catch (SomeException ex) {
... error stuff...
repeat = true;
}
while (repeat);
This is (a) makes the loop termination clearer than arbitrary jumps ('break') out of the loop, and (b) makes it trivial when you find you have other reasons to re-do the loop body.

How can I solve this program in another way? I want to know the type of input given by user

This is the program that I have written & I want to solve this in some other way. I dont want to use the try-catch statement.
I have researched about the other waya but it was not clearly explained.
import java.io.*;
import java.util.*;
public class TPJava {
public static void main(String args[]) throws Exception {
Scanner scan = new Scanner(System.in);
try {
int int_var = scan.nextInt();
System.out.println("It is an Integer.");
}
catch (InputMismatchException e)
{
try
{
String str_var = scan.next();
System.out.println("It is a String");
}
catch (InputMismatchException ie)
{
try
{
Float f = scan.nextFloat();
System.out.println("It is Float");
}
catch (InputMismatchException ime)
{
System.out.println("Wrong Input.");
}
}
}
}
}
if (XXX instanceof int)
{
System.out.println("It is an integer.");
}
else if (XXX instanceof String)
{
System.out.println("It is a string.");
}
....
(and so on)
EDIT:
found a solution that should work for exactly your code.
Scanner scan= new Scanner(System.in);
if(scan.hasNextInt())
{
System.out.println("It is an integer.");
}
else if (scan.hasNextFloat())
{
System.out.println("It is a Float.");
}
....
else
{
System.out.println("It is a String.");
}
this checks if the next variable can be interpreted as a integer/float/ etc.....
i think there is none for "String" so i just used the "else" statement there
BUT: you have to user scan.next() or nextInt or something like that afterwards, else it will continuesly use the same input over and over again (i assume)

Understanding try & catch and error handling

import java.util.Scanner;
public class Lab4_5 {
public static void main(String[]args) {
Scanner scan= new Scanner(System.in);
int rows=0;
int rowIndex=0, colIndex=0;
boolean choice1= true;
String y="y";
String n="n";
boolean first = true;
while (choice1==true) {
if (first==true) {
first=false;
System.out.println("Do you want to start(Y/N): ");
} else if (first==false) {
System.out.println("Do you want to continue(Y/N): ");
}
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
System.out.println("What character?");
String choice3=scan.next();
System.out.println(" ");
for (rowIndex=1; rowIndex<=rows; rowIndex++) {
for (colIndex=1; colIndex<=rows; colIndex++) {
if (rowIndex==1 || rowIndex==rows || colIndex==1 || colIndex==rows) {
System.out.print(choice3);
} else {
System.out.print(" ");
}
}
System.out.println();
}
} else if(choice2.equals(n)) {
choice1 = false;
System.out.println("Thank you. Goodbye.");
} else {
System.out.println("Please either enter Y or N.");
}
}
}//end of main
}
The code prints what I need it to print, but I also have to have something in the code when it asks how many rows/columns to catch whether or not i input something other than an integer(in the part below). need some help, we haven't done anything yet with how to catch exceptions and i don't know how to start.
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
}
You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
In your particular case you can have the following exceptions (link).
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}
You can create a try-catch block like so:
try {
int num = scan.nextInt();
} catch (InputMismatchException ex) {
// Exception handling here
}
If you want to implement this in your code, I suggest doing this:
while (true) {
try {
rows = scan.nextInt();
if (rows<5||rows>21) {
break;
}
else {
System.out.println("That is either out of range or not an integer, try again! ");
}
} catch (InputMismatchException ex) {
System.out.println("That is either out of range or not an integer, try again! ");
}
}
See here for more details.
String choice2=scan.next();
if(choice2.equals(y)){
System.out.println("How many rows/columns(5-21)?");
try
{
rows=scan.nextInt();
}catch(Exception e)
{
rows = -1;
}
while(rows<5||rows>21){
System.out.println("That is either out of range or not an integer, try again! ");
try
{
rows=scan.nextInt();
}catch(Exception e)
{
rows = -1;
}
}

Three exceptions for int

I am trying to create a code where an int is supposed to be entered and then have exceptions for if the int is not between 9 and 99, another exception if a double is entered instead of int and then a third exception if a string is entered. How do i do this? i have below what i have so far but am not sure how to correct it. thanks
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean correct = true;
do {
try {
System.out.println("Enter an Integer between 9 and 99");
int number = input.nextInt();
if (number >= 9 && number <= 99) {
System.out.println("Thank you, Initialization completed");
correct = false;
} else if (number < 9 || number > 99) {
throw new Exception("Integer is not within the range");
}
if (input.hasNextDouble()) {
throw new Exception("Integer not entered");
} else {
correct = false;
}
if (input.hasNext("")) {
throw new NumberFormatException("Integer not entered");
} else {
correct = false;
}
} // check for range
catch (Exception e1) {
System.out.println("Number is not within 9 and 99");
System.out.println();
input.nextLine();
} catch (Exception e2) {
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
} catch (NumberFormatException e3) {
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
}
} while (correct);
}
Method .getMessage() returns the string given in constructor:
throw new Exception("HERE");
When you catch Exception, you catch also NumberFormatException, InputMismatchException, etc.
so you must catch broader ones last.
catch (NumberFormatException e3) { // Precisier goes first
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
}
catch (Exception e1) {
System.out.println(e1.getMessage());
System.out.println();
input.nextLine();
}

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories