JavaAPI-スキャナークラス



Java Api Scanner Class



1、スキャナークラスの概要

JDK5は、後でユーザーのキーボード入力を取得するために使用されます。これは、正規表現を使用して基本的な型と文字列を解析できる単純なテキストスキャナーです。 Scannerは、セパレータモードを使用して、入力をトークンに分割します。トークンは、デフォルトで空白と一致します。次に、別のnextメソッドを使用して、結果のマークを別のタイプの値に変換できます。 2、現在使用されている構築メソッドpublic Sc​​anner(InputStream source)3、Scannerクラスのメンバーメソッド1)基本形式hasNextXxx()は、別のエントリがあるかどうかを判別します。次の文字列が含まれるかどうかを判断する場合は、Xxxを省略できます。 nextXxx()次のエントリを取得します。 Xxxの意味は、前の方法のXxxと同じです。 2)デフォルトでは、スキャナーはスペース、キャリッジリターンなどを区切り文字として使用します。 3)例:int型メソッドを使用する
public boolean hasNextInt() public int nextInt()
public class ScannerDemo { public static void main(String[] args) { // Create object Scanner sc = new Scanner(System.in) // Get the data, first determine whether the input data matches the type of the received variable if (sc.hasNextInt()) { int x = sc.nextInt() System.out.println('x:' + x) } else { System.out.println('The data you entered is incorrect') } } }
4)次の2つのメソッドを組み合わせて使用​​することを分析します。publicintnextInt()public String nextLine()最初に値を取得してから文字列を取得すると、問題が発生します。主な理由:改行記号の問題。 解決した問題:A:値を取得した後、新しいキーボード入力オブジェクトを作成して文字列を取得します。 B:最初に文字列に従ってすべてのデータを取得し、次に何、対応する変換を取得します。
public class ScannerDemo { public static void main(String[] args) { // Create object Scanner sc = new Scanner(System.in) // Get two values ​​of type int int a1 = sc.nextInt() int b1 = sc.nextInt() System.out.println('a:' + a1 + ',b:' + b1) System.out.println('-------------------') // Get two values ​​of type String String s1 = sc.nextLine() String s2 = sc.nextLine() System.out.println('s1:' + s1 + ',s2:' + s2) System.out.println('-------------------') // Get a string first, get an int value String s3 = sc.nextLine() int b2 = sc.nextInt() System.out.println('s1:' + s3 + ',b:' + b2) System.out.println('-------------------') // Get an int value first, get a string, get the data wrong int a2 = sc.nextInt() String s4 = sc.nextLine() System.out.println('a:' + a2 + ',s2:' + s4) System.out.println('-------------------') //Workaround: Define two Scanner objects to get the data twice int a = sc.nextInt() Scanner sc2 = new Scanner(System.in) String s = sc2.nextLine() System.out.println('a:' + a + ',s:' + s) } }

転載:https://www.cnblogs.com/yangyquin/p/4934146.html