English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaのメソッドでScannerオブジェクトを引数として渡す文法は何ですか?

Java 1.5ユーザープログラマーからデータを読み取る前に、すべてが文字ストリームクラスとバイトストリームクラスに依存しています。

Javaから 1.5Scannerクラスの導入を開始します。このクラスはFile、InputStream、Path、Stringオブジェクトを受け取り、正規表現を使用して、すべての原始データタイプとString(指定されたソースから)のトークンを順次読み取ります。

デフォルトでは、スペースが区切り文字(データをトークンに分ける)とされています。

さまざまなデータタイプのデータをソースから読み取りますnextXXX()このクラスは提供するメソッドによってnextInt()nextShort()nextFloat()nextLong()nextBigDecimal()nextBigInteger()nextLong()nextShort()nextDouble()nextByte()nextFloat()next()

Scannerオブジェクトをパラメータとして渡す

Scannerオブジェクトをメソッドにパラメータとして渡すことができます。

以下のJavaプログラムは、Scannerオブジェクトをメソッドに渡す方法を示しています。このオブジェクトはファイルの内容を読み取ります。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ScannerExample {
   public String sampleMethod(Scanner sc){
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.nextLine());
      }
      return sb.toString();
   }
   public static void main(String args[]) throws IOException {
      //inputStreamクラスをインスタンス化します
      InputStream stream = new FileInputStream("D:\\sample.txt");
      //Scannerクラスのインスタンス化
      Scanner sc = new Scanner(stream);
      ScannerExample obj = new ScannerExample();
      //呼び出し方法
      String result = obj.sampleMethod(sc);
      System.out.println("ファイル内容:");
      System.out.println(result);
   }
}

输出結果

ファイル内容:
oldtoolbag.com originated from the idea that there exists a class of readers who respond better to on-line
content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.

以下の例では、標準入力(System.in)をソースとして持つScannerオブジェクトを作成し、それをメソッドにパラメータとして渡します。

import java.io.IOException;
import java.util.Scanner;
public class ScannerExample {
   public void sampleMethod(Scanner sc){
      StringBuffer sb = new StringBuffer();
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your age: ");
      String age = sc.next();
      System.out.println("Hello "+name+" You are "+age+" years old");
   }
   public static void main(String args[]) throws IOException {
      //Scannerクラスのインスタンス化
      Scanner sc = new Scanner(System.in);
      ScannerExample obj = new ScannerExample();
      //呼び出し方法
      obj.sampleMethod(sc);
   }
}

输出結果

Enter your name:
Krishna
Enter your age:
25
Hello Krishna You are 25 years old