• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Only allow Strings to be Scanned with scanner.

 
Karl Collins
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49793
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also the nextLine() method doesn’t do what most people think it does. Look at this old post.
 
Randall Twede
Ranch Hand
Posts: 4467
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49793
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic