-
Exception Handling
So a while back I learnt about exception handling in Java, but only now I have put it to use. Here is my code, I am catching an exception where the user may input a incorrect character.
Code:
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber
{
public static int randomNumber;
public static int guessedNumber;
static Random rand = new Random();
static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
randomNumber = rand.nextInt(100);
update();
}
public static void update()
{
guessedNumber = getInput();
checkInput();
}
public static int getInput()
{
guessedNumber = 0;
int returnNum = 0;
System.out.println("Enter a number between 1-100!");
try
{
returnNum = input.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("There was an exception: " + e);
getInput();
}
return returnNum;
}
public static void checkInput()
{
if(guessedNumber == randomNumber)
{
System.out.println("Correct number! You win the game!");
System.exit(0);
}
else if(guessedNumber < 0 || guessedNumber > 100)
{
System.out.println("What are you playing at?");
}
else if(guessedNumber > randomNumber)
{
System.out.println("A little lower.");
}
else if(guessedNumber < randomNumber)
{
System.out.println("A little higher.");
}
update();
}
}
And here is my output when I enter an incorrect character, it just spams me with this, and the program exits.
Since the output is too big, I have put it on Pastebin (Click Me)
Please could anyone tell me what I'm doing wrong?
Regards,
- Bicentric
-
Re: Exception Handling
You should write a better code.
Fast solution for one part of your program problems is:
Code:
System.out.println("Enter a number between 0 and 100");
try {
returnNum = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("Warning: Only allowed characters are 0-9");
System.exit(0);
//getInput();
}
return returnNum;
But my advice for you is that you should write your program again. It's bad practice to call your method getInput() inside same method (recursion) when you can use for example for or while loop for calling your method. It's faster, it's better, code are more elegant.