If I need a string or an int from the user, how can I make sure that that is what they inputted?

The lame way of putting EVERYTHING in strings and then somehow check?
Or maybe throw-catch?

I tried the try-catch but had a few problems.
The examples I saw only had a try and a catch, no throw.
When I did it like that, it said that no exception was being thrown.

And how are you supposed to know what type of Exception it is?
If I want user input, I'm guessing it's IOException?
Or I saw something along the lines of "Mismatch"something..

So how can I check?
I guess I also need a while loop or do-while loop for every input, so that it will ask the user again if they input something they're not supposed to......

Recommended Answers

All 32 Replies

If I need a string or an int from the user, how can I make sure that that is what they inputted?

Read it as a String
and then use the Integer parseInt() method inside of a try/catch block to validate it.
Or scan it character by character and test if each character is a numeric digit.

readInt and readLine (except this could be numbers as well maybe use a for loop to see if each character is a letter)

Read it as a String
and then use the Integer parseInt() method inside of a try/catch block to validate it.
Or scan it character by character and test if each character is a numeric digit.

A try catch doesnt seem to work for me?
How should it look like?

This is my code

import java.util.Scanner;

public class main
{
	public static void main(String[] argv)
	{		
		Scanner scn = new Scanner(System.in);
		x100race Race = new x100race();
		
		while(true)
		{
		System.out.println(
				"1. Enter data\n" +
				"2. Display all data\n" +
				"3. Search name and display their time\n" +
				"4. Search for the best time and display name and time\n" +
				"5. Exit program"
						);
		
		System.out.print("Your choice?: ");
		
			
		switch( scn.nextInt() )
		{
		case 1:
			Race.enterData();
			break;
		case 2:
			Race.displayData();
			break;
		case 3:
			Race.searchNameAndDisplayTime();
			break;
		case 4:
			Race.searchBestTimeAndDisplayNameAndTime();
			break;
		case 5:
			System.exit(0);
			break;
		default:
			System.out.println();
			System.out.println("Learn to read! A number between 1 and 5, dumbo.");
			System.out.println();
		}
		}
		
		
	}

}

The "switch ( scn.nextInt() )" part is one of the places I would like a try-catch, because if you input a letter it will just bug out and give a bunch of errors.

Move the call to nextInt to a separate statement that assigns the value being read to an int variable. Then you can put that statement within a try{}catch block.

Move the call to nextInt to a separate statement that assigns the value being read to an int variable. Then you can put that statement within a try{}catch block.

Changed part of the code to:
I also imported java.io.IOException

while(true)
		{
			try
				{
				 menuChoice = scn.nextInt();
				}
			catch (IOException e)
				{
				 System.out.println("Error occured!");
				}
			if(menuChoice > 0 && menuChoice < 6)
				break;		
		}
		
		switch( menuChoice ) 
		{
		case 1:

IOException is red, saying " Unreachable catch block for IOException. This exception is never thrown from the try statement body "

This exception is never thrown from the try statement body

The compiler does not see where an IOException can be thrown in the try statement.
Where did you see that the nextInt method would throw that exception?
To see what exceptions the nextInt method can throw, read the API doc.
At the bottom of the section for the nextInt method, there are a list of the exceptions that the nextInt method can throw. You should chose one or more of those to catch.

Another approach to making sure you get an integer is to use the hasNextInt method to test if the user has entered a valid integer value.

The compiler does not see where an IOException can be thrown in the try statement.
Where did you see that the nextInt method would throw that exception?
To see what exceptions the nextInt method can throw, read the API doc.
At the bottom of the section for the nextInt method, there are a list of the exceptions that the nextInt method can throw. You should chose one or more of those to catch.

Another approach to making sure you get an integer is to use the hasNextInt method to test if the user has entered a valid integer value.

I tried a simple

if(scn.hasNextInt())
			System.out.println("Is int");
		else
			System.out.println("Aint no int");

which seemed to work fine.

Also, I just thought it would be a IOException since thats the only thing I had heard about.
Checked the list thing in the IDE, said which errors could be thrown.
Thanks.

I've seen like try, catch, finally or something.
What does that do?

Oh and.. What happends if you write Throws IOException here:
blabla.... main(String[] args) throws IOException {....}

Go to this site and read all about them:
http://download.oracle.com/javase/tutorial/essential/TOC.html

Seem to have a problem with the has nextInt solution.
Or well, it's probably sometihng else

import java.util.Scanner;

public class main
{
	public static void main(String[] argv)
	{		
		Scanner scn = new Scanner(System.in); 
		x100race Race = new x100race(); 
		int menuChoice = 0;
		
		while(true)
		{
		System.out.println(
				"1. Enter data\n" +
				"2. Display all data\n" +
				"3. Search name and display their time\n" +
				"4. Search for the best time and display name and time\n" +
				"5. Exit program"
						);
		
		System.out.print("Your choice?: ");
		
		do
		{
			if( scn.hasNextInt() )
				menuChoice = scn.nextInt();
			else
				System.out.println("Error! Need a number between 1 and 5.");
		}while(menuChoice < 1 || menuChoice > 5);
		
		
		switch( menuChoice ) 
		{
		case 1:
			Race.enterData(); 
			break;
		case 2:
			Race.displayData();
			break;
		case 3:
			Race.searchNameAndDisplayTime();
			break;
		case 4:
			Race.searchBestTimeAndDisplayNameAndTime();
			break;
		case 5:
			System.exit(0);
			break;
		default:
			System.out.println();
			System.out.println("Learn to read! A number between 1 and 5, dumbo.");
			System.out.println();
		}
		}
		
		
	}

}

It just keeps repeating "Error! Need a number between 1 and 5."

I see the problem, I suppose, but not sure how to solve it

Add a println line to show what the value of the variable is.

What are you typing in at the console?
If you type in a letter, that letter will stay in the Scanner's buffer until you read it out with some next... method.
As long as the letter is in the buffer, hasNextInt() will always return false.

Add a println line to show what the value of the variable is.

What are you typing in at the console?
If you type in a letter, that letter will stay in the Scanner's buffer until you read it out with some next... method.
As long as the letter is in the buffer, hasNextInt() will always return false.

I tried stuff like 3.0 and h.

This kind of worked:

System.out.print("Your choice?: ");
		
		do
		{
			if( scn.hasNextInt() )
				menuChoice = scn.nextInt();
			else{
				System.out.println("Error! Need a number between 1 and 5.");
				scn.nextLine();
				}
			
		}while(menuChoice < 1 || menuChoice > 5);

If i first enter h, it will say error then since I dont have a "You're choice?" again, it will just be blank and wait for an input.

If I chose an option, say, 3, it will say: No data availible to do a search (as it should say) and then it goes back to main, prints out the menu again and says no data availible again...

Looking into how to solve it >_>

If i enter 3, and then a letter, this is the output:

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: 3


No data availible. Sorry.

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: f
Error! Need a number between 1 and 5.


No data availible. Sorry.

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: Error! Need a number between 1 and 5.


No data availible. Sorry.

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?:

Did you remember to reset the value used to keep you in the while loop?

Did you remember to reset the value used to keep you in the while loop?

I did now, still acts a bit weird...

The code now is

public static void main(String[] argv)
	{		
		Scanner scn = new Scanner(System.in); 
		x100race Race = new x100race();
		int menuChoice = 0;
		
		while(true) //Epic menu
		{
			menuChoice = 0;
			
		System.out.println(
				"1. Enter data\n" +
				"2. Display all data\n" +
				"3. Search name and display their time\n" +
				"4. Search for the best time and display name and time\n" +
				"5. Exit program"
						);
		
		
		do
		{
			System.out.print("Your choice?: ");
			
			if( scn.hasNextInt() )
				menuChoice = scn.nextInt();
			else{
				System.out.println("Error! Need a number between 1 and 5.");
				scn.nextLine();
				}
			
		}while(menuChoice < 1 || menuChoice > 5);
		
		
		switch( menuChoice ) 
		{
		case 1:

The output is:

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: f
Error! Need a number between 1 and 5.
Your choice?: 2
//Works as expected so far

No data availible. Sorry.

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: d
Error! Need a number between 1 and 5. //here it were it goes weird, I get the error message twice, once here
Your choice?: Error! Need a number between 1 and 5. //and once here. What the hell? ; ( I didn't input anything here
Your choice?:

still acts a bit weird...

You need to explain if there are problems by adding some comments to the output.

You need to explain if there are problems by adding some comments to the output.

done

Ok, glad you got it working.

Ok, glad you got it working.

I didn't.
By "Done" i mean I added comments to the ouput.
I get the error message twice, like if theres still stuff in the input stream/vuffer/whatever.

For debugging, save what nextLine reads in a variable and print it out. Be sure to put a String before and after what you read when you print it. Something like: (">" + dataRead + "<")

For debugging, save what nextLine reads in a variable and print it out. Be sure to put a String before and after what you read when you print it. Something like: (">" + dataRead + "<")

Hm...
Weird..

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: a
Error! Need a number between 1 and 5.
>a<
Your choice?: 2

No data availible. Sorry.

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: x
Error! Need a number between 1 and 5.
><
Your choice?: Error! Need a number between 1 and 5.
>x<
Your choice?:

That is showing you the buffering that the Scanner class does.
Here is what I think happened: When you read the 2, the new line was left in the buffer.
The nextLine read that and displayed it at line 20.

Bottom line: You need to clear the buffer by calling nextLine after calling nextInt

That is showing you the buffering that the Scanner class does.
Here is what I think happened: When you read the 2, the new line was left in the buffer.
The nextLine read that and displayed it at line 20.

Bottom line: You need to clear the buffer by calling nextLine after calling nextInt

Works perfectly.
Stupid int and strings, huh?
Silly scanner.

The Scanner class can be useful but does take some care.
But that is true of most programmming.
Welcome aboard.

The Scanner class can be useful but does take some care.
But that is true of most programmming.
Welcome aboard.

For crying out loud, what the hell is the problem now!

do
		{
		System.out.print("Would you like to delete the data to input new data? <y/n>: ");	
		 
		 answer = scan.nextLine();
		 
		 if(answer.compareToIgnoreCase("n")==0)
				 return;
		 else if(answer.compareToIgnoreCase("y")==0)
			  	 deleteEntries();
		 
		 else{
			 System.out.println("Error! Enter y or n!");
		 	 }
		 
		}while(answer.compareToIgnoreCase("y")==1 && answer.compareToIgnoreCase("n")==1);
		
		}
		
		int numbah = 0;
		
		do
		{
			System.out.print("How many names and times would you like to enter?: ");

When it asks if i want to delte the old data, it wants y or n.
If i write a number or another letter, it will jump to "How many names and times..."
What the hell?

The output is:

1. Enter data
2. Display all data
3. Search name and display their time
4. Search for the best time and display name and time
5. Exit program
Your choice?: 1

Data already exists.
 
Would you like to delete the data to input new data? <y/n>: x
Error! Enter y or n!
How many names and times would you like to enter?:

the variable answer does get the value that was entered, in this case , x.
But it still jumps to "How many times.." ;S

answer.compareToIgnoreCase("y")==1

What does this do? Have you printed out what that method returns? Why are you testing if is is a 1? 1 is the value for 'x' vs 'y', try the code with other letters to see what you get.
Instead of using compareTo() you could use equals()

What does this do? Have you printed out what that method returns? Why are you testing if is is a 1? 1 is the value for 'x' vs 'y', try the code with other letters to see what you get.
Instead of using compareTo() you could use equals()

Hm.. I don't really know where I got 1 from o.O
!= 0 should work instead.

I'm using compare to because I want to ignore case, does equals do that?

Yup, it works now.
I changed ==1 to != 0

But doing this is annoying, its a lot of code for each check.
Isn't there an easier way? Perhaps the try/catch thing...

And what if I need a name, how do i check it is all letters?

I'm using compare to because I want to ignore case, does equals do that?

There is a String method that will do that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.