d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Need Java .nextint() Not Advancing In Method Help
Add Reply New Topic New Poll
Member
Posts: 595
Joined: Mar 7 2008
Gold: 29.10
Nov 12 2012 02:15pm
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
Member
Posts: 4,605
Joined: Sep 15 2011
Gold: 9,464.00
Nov 12 2012 02:23pm
because aa is not an int, so your scanner never moves past the aa input, so your if statement keeps returning false, and your getInRange method keeps returning -1.

the most obvious way to see this would be to write out the state on pen and paper, and simulate the code execution by hand. you'll see that your scanner object is always reading in "aa" when you call hasNextInt.


what the hell is
Code
int x=-1;

supposed to do?

This post was edited by irimi on Nov 12 2012 02:26pm
Member
Posts: 595
Joined: Mar 7 2008
Gold: 29.10
Nov 12 2012 02:29pm
Forgot to cut that out, was an artifact.
T_T Such a simple concept, thanks for the help :).
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll