Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Making a methoed to validate input - try/catch InputMismatchException

843785Nov 11 2008 — edited Nov 11 2008
I need to set up a method that will validate input from the keyboard and ensure that only int values are entered before passing it on.

I have succesfully set up the method to check if the values are within bounds (specified when the method is called), but I need to use exception handling, which I am not very experienced using, in order to make sure that the user do not enter a string or something else which will throw an exception.

If the user enters a string a InputMismatchException is thrown, but for some reason I cannot handle this exception. It seems that I can compile the code if try to handle other exceptions but this one won't work.

I am using Eclipse and currently it indicates this error at the line where my catch-statement is located:

"Multiple markers at this line
- Duplicate parameter exception
- InputMismatchException cannot be resolved to a type"


This is my current attempt:



//Method for input validation
	
	private static int inputData(int min, int max)
	{
	
		int input = 100;
		String exception;
		
	do {
	do {
	


		try{	
	input = tastatur.nextInt();
		}
	
		catch (InputMismatchException exception)
		{
			System.out.println("Only numeric values may be used. Exception: " + exception);
		}
	
	if (input > max)
	{
		System.out.println("Invalid value, choose a value between " + min + " and " + max + " try again");	
	}else{
		if (input < min)
		{
		System.out.println("negative values may not be used. Choose a value between " + min + " and " + max + " try again");	
		}
	
	
	}
	
	
	
	} while (input > max);
	} while (input < min);
	
		return input;
	
	}
EDIT: BTW I don't get an error message if I try to catch for a different exception. NumberFormatException for instance, but it doesn't really help me since it is not the exception thrown.

Edited by: He_Who_Knows on Nov 11, 2008 4:11 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 9 2008
Added on Nov 11 2008
3 comments
557 views