I need to enter the time in the format seen in line 4, all is good. But when in line 8,9,10 when I pass tokens to getInRange with timeTmp being 12:13:14.
S.o.pln --> 12 13 14
But when I enter 12:aa:14 into timeTmp and pass it to getInRange.
S.o.pln --> 12 -1 -1.
And if I enter aa:13:14
> -1 -1 -1
My question is why isn't my tokens advancing to the next position when it encounters
if (tokens.hasNextInt())
{
...
}
and a variable is variable is false. But it works for when everything is true.
(It returns -1 for x, and even though y and z are valid, tokens.hasNextInt() appears to be false and it goes ahead and returns -1)
Code
public static void main(String[] args)
{
String timeTmp;
timeTmp = JOptionPane.showInputDialog(null,"Enter the time in format hh:mm:ss (0-23:0-59:0-59)");
Scanner tokens = new Scanner (timeTmp);
tokens.useDelimiter(":");
int x = getInRange(tokens,0,24);
int y = getInRange(tokens,0,59);
int z = getInRange(tokens,0,59);
System.out.println(x + " " + y + " " + z);
}
public static int getInRange (Scanner tokens, int low, int high)
{
int x=-1;
if (tokens.hasNextInt())
{
return tokens.nextInt();
}
return -1;
}
Code
Entered: 12:13:14 -> 12 13 14
Entered: 12:aa:14 -> 12 -1 -1
Entered: aa:13:14 -> -1 -1 -1