0

I'm used to checking if a user inputs a double or a integer with input.hasNextDouble/input.hasNextInt and then assigning a variable if this is true with input.nextDouble()/input.nextInt().

But now I want to check if the input is a String or not, and if so, assign my variable, and if not, produce an error message and loop again. Is there an equivalent method/statement like this for Strings in Java? Or another way to do so?

dimo414
  • 47,227
  • 18
  • 148
  • 244
Clarisa
  • 125
  • 2
  • 12
  • 4
    `"But now I want to check if the input is a String or not,..."` -- the input is always a String, either that or empty, but even that is an empty String `""` -- please clarify **exactly** what you're testing. – Hovercraft Full Of Eels Oct 19 '15 at 01:26
  • 4
    So is `"1234"` a `String`? – MadProgrammer Oct 19 '15 at 01:26
  • http://stackoverflow.com/questions/29692089/how-to-check-if-user-input-is-string-double-or-long-in-java has numerous explanations/ways of checking for numerical input – peter Oct 19 '15 at 01:30
  • http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java Check this – Yassin Hajaj Oct 19 '15 at 01:44

2 Answers2

0

A Scanner allows you to read in text from some sort of input (e.g. a file or an InputStream). That text is naturally a String (because it's a sequence of bytes, which Scanner interprets as characters). You can read the strings with .next() and .nextLine(), which read a single "word" token or a single line at a time, and which you can inspect with hasNext() and hasNextLine().

Scanner also provides the primitive methods as a convenience for reading in tokens that can be safely converted into primitives (e.g. int and double), so that you don't have to write convoluted integer-parsing code and the like.

But if all you need is strings, just use hasNext() and next(), or hasNextLine() and nextLine(). There is no need to check whether the input is a String or not, because anything the user types is a string. Be sure to read the docs describing how Scanner splits words/tokens up as well.

dimo414
  • 47,227
  • 18
  • 148
  • 244
-3

If you use an IDE like Eclipse, it should show you the options after you type input.. Anyway, the boolean check for strings in the Scanner class would either be:

input.hasNext();

or

input.hasNext();

where input is an instance of the Scanner class

Krusty the Clown
  • 517
  • 6
  • 24