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".

有帮助吗?

解决方案

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
    }
}

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top