wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Only allow Strings to be Scanned with scanner. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Only allow Strings to be Scanned with scanner." Watch "Only allow Strings to be Scanned with scanner." New topic
Author

Only allow Strings to be Scanned with scanner.

Karl Collins
Greenhorn

Joined: Nov 22, 2011
Posts: 21
Hi,

So I was under the impression that the line of code below would only allow Strings to be entered.
What I'm asking is how do I make it so the user can only enter strings.



I thought "s1 = userin.nextInt" would only allow int's to be entered.

I read up on some links somebody gave me here but I cant seem to find the answer.
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Karl Collins wrote:
What I'm asking is how do I make it so the user can only enter strings.....
I thought "s1 = userin.nextInt" would only allow int's to be entered.

Integers, special chars can be a part of a String. Hence you have to validate the input for the name and alert the user / throw exception if it constitutes char you don't expect.

nextInt() method parses the scanner's input as an int. It returns the int but does not force you to enter only integer value. If you enter a non-integer, you will get an Exception.
Hence it's safe to pre-check the scanner's input with the hasNextInt() method before using nextInt().
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38087
    
  22
Also the nextLine() method doesn’t do what most people think it does. Look at this old post.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

interesting...Campbell, why do you say a constructor is not a method? yeah, i'm baiting you i suppose, but it seems to me a constructor is just a method with no return value given(i.e. void). oh wait...it also starts with a capital letter....maybe it is that different after all.


SCJP
Visit my download page
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38087
    
  22
Constructors are different from methods. You can call methods on objects (or on classes, if static), but you can’t call constructors thus.
A method does something with an object, and a method helps set up the object’s initial state.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Only allow Strings to be Scanned with scanner.
 
Similar Threads
How many String Object are created in the following code ??
multiple inputs
"-1 if this list does not contain the element." problem using arraylist
Threads
WHEN ARE TWO STRINGS EQUAL?