Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6223711

Caching error in java.util.Scanner class

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 6
    • 5.0
    • core-libs
    • b25
    • x86
    • windows_2000

      FULL PRODUCT VERSION :
      java version "1.5.0_01"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
      Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows 2000 [Version 5.00.2195]

      A DESCRIPTION OF THE PROBLEM :
      Caching integer values doesn't take the radix into account. Calling haxNext(16) followed by next(10) will give an incorrect result.


      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------

      import java.util.Scanner;

      public class ScannerBug {

      public static void main(String args[]) {
      String data = "10";

      Scanner s = new Scanner(data);
      if (s.hasNextInt(16))
      System.out.println("Value: " + s.nextInt(10));

      s = new Scanner(data);
      System.out.println("Value: " + s.nextInt(10));
      }

      }
      ---------- END SOURCE ----------

      The actual result is:
      - --------------
      Value: 16
      Value: 10
      - --------------

      The expected result is:
      - --------------
      Value: 10
      Value: 10
      - --------------

      as the hasNext(16) will correctly detect an hexadecimal integer (0x10)
      but the following code to "next(10)" should read the same string as a
      base 10 integer but instead used the cached value of 0x10, i.e. 16.

      The second code is just to show that calling the scanner on the same
      input string without the side effect of "hasNext(16)" will produce the
      correct result.

      I know I should have used some other input string as it's confusing a
      little bit as 10 and 16 are also the values of the radixes. Maybe, if
      you change 'String data = "14"', you'll see that the result becomes 20
      instead of 14 in the first call to "next(10)".
      ###@###.### 2005-1-31 21:21:54 GMT

            sherman Xueming Shen
            rmandalasunw Ranjith Mandala (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: