How do i change this method to get strings instead of ints
- by David
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?