Question

   public static void main(String argv[]){
         String a="0700";
         Scanner s = new Scanner(a);
         while(s.hasNextLong()){
              System.out.print(s.nextLong()+",");
         }

Result will be "700," not the "448".

Était-ce utile?

La solution

By default the scanner assumes that the number is in base 10 and will ignore the leading 0s. You can specify another radix if you want - the code below prints 448:

public static void main(String[] args) {
    String a = "0700";
    Scanner s = new Scanner(a);
    while (s.hasNextLong(8)) { //make sure the number can be parsed as an octal
        System.out.print(s.nextLong(8)); //read as an octal value
    }
}

Autres conseils

You can set default radix using Scanner#useRadix(radix) method or pass radix explicitly to Scanner#hasNextLong(radix) and Scanner#nextLong(radix) methods.

Read the documentation. It says that it will use the default radix of the Scanner. If the default is not acceptable then you can change it with the useRadix(int radix) method or use the nextLong(int radix) for a temporary change in radix.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top