Why we love java

Edd, Dave and Me just spend 2 hours figuring out how the java.util.Scanner class works. This was based on this little example
 1    public static void main(String[] args) {
2 Scanner sc = new Scanner(System.in);
3 System.out.println("1: ");
4 String l1 = sc.nextLine();
5 System.out.println("2: ");
6 int l2 = sc.nextInt();
7 System.out.println("3: ");
8 String l3 = sc.nextLine();
9 }
What would you expect this to do? Like everyone with some sort of logical thinking mind you would assume that this would ask you for some sort of a String which you terminate with Enter then for a number with again you terminate with Enter and then another String. Run it and have a look. You will be amazed. It never asks you for the '3:' value? So why is this? Because if you call nextLine it will still leave some stuff in the buffer. This is then not returned by nextInt() as it is a String. So you are prompted to insert a int. But when it comes to the third read it will notice it still has something in it's buffer and return that. Even if there is nothing
System.out.println("_" + l3 + "_");
will open your eyes. You have to love the bad design of the Java libraries. We had something similar in ruby where we passed in a String that was not chomped to exists?
Another thing that caught us out in the scanner class is the hasNext. From the java source code of public boolean hasNext()
if (hasTokenInBuffer())
return revertState(true);
So if there is something in the buffer return if not wait for input. That is really what you expect from this. I can see my self testing if there is something in the buffer with hasNext(). As this is what every sensible person would assume. But no, the people at Sun see this different. So what do we learn from this?
=> Before anything look at the api documentation as there is no standard here and you will read

* Returns true if this scanner has another token in its input.
* This method may block while waiting for input to scan.
* The scanner does not advance past any input.

1 comment:

leechsluckers said...
This comment has been removed by a blog administrator.