How do i change this method to get strings instead of ints
Posted
by David
on Stack Overflow
See other posts from Stack Overflow
or by David
Published on 2010-03-26T00:17:12Z
Indexed on
2010/03/26
0:23 UTC
Read the original article
Hit count: 301
here is the original code:
public static int getInt ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextInt())
{
int a = in.nextInt() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getInt () ;
}
}
This checks and sees if the input it receives is an int. If it is then it returns the int, if not it tells you to try again and re-runs.
This is what i tried to do to change it:
public static String getIns ()
{
Scanner in = new Scanner (System.in) ;
if (in.hasNextString())
{
String a = in.nextString() ;
return a ;
}
else
{
System.out.println ("try again:") ;
return getIns () ;
}
}
This doesn't work though. I looked through the documentation for the scanner class and i think the problem is that there is no such method as in.hasNextString
or in.nextString
What methods from the scanner class can i use to do what i intend these to do?
© Stack Overflow or respective owner