Java Scanner useRadix() 方法



描述

java Scanner useRadix(int radix) 方法將此掃描器的預設基數設定為指定的基數。

宣告

以下是 java.util.Scanner.useRadix() 方法的宣告

public Scanner useRadix(int radix)

引數

radix − 掃描數字時使用的基數

返回值

此方法返回此掃描器

異常

IllegalArgumentException − 如果基數超出範圍

在字串示例上設定掃描器的基數

以下示例演示瞭如何使用 Java Scanner useRadix(int radix) 方法為掃描器使用基數。我們使用給定字串建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個區域設定來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6.0 true ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // print a line of the scanner
      System.out.println(scanner.nextLine());

      // change the radix of this scanner
      scanner.useRadix(4);

      // display the new radix
      System.out.println(scanner.radix());

      // close the scanner
      scanner.close();
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Hello World! 3 + 3.0 = 6.0 true 
4

在使用者輸入示例上設定掃描器的基數

以下示例演示瞭如何使用 Java Scanner useRadix(int radix) 方法設定掃描器的基數。我們使用 System.in 類建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個基數來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      // create a new scanner with the System.in class
      Scanner scanner = new Scanner(System.in);

      // print a line of the scanner
      System.out.println(scanner.nextLine());

      // change the radix of this scanner
      scanner.useRadix(4);

      // display the new radix
      System.out.println(scanner.radix());

      // close the scanner
      scanner.close();
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

3
3
4

在屬性檔案示例上設定掃描器的基數

以下示例演示瞭如何使用 Java Scanner useRadix(int radix) 方法設定掃描器的基數。我們使用 properties.txt 檔案建立了一個掃描器物件。我們使用 nextLine() 方法列印了一行,然後設定了一個基數來列印它。然後使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) throws FileNotFoundException {

      // create a new scanner with a file as input
      Scanner scanner = new Scanner(new File("properties.txt"));

      // print a line of the scanner
      System.out.println(scanner.nextLine());

      // change the radix of this scanner
      scanner.useRadix(4);

      // display the new radix
      System.out.println(scanner.radix());

      // close the scanner
      scanner.close();
   }
}

假設我們在你的 CLASSPATH 中有一個名為 properties.txt 的檔案,其內容如下。此檔案將用作我們示例程式的輸入:

Hello World! 3 + 3.0 = 6

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Hello World! 3 + 3.0 = 6
4
java_util_scanner.htm
廣告