سؤال

   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