スキャナーは文字列を入力できません
文字列を入力するには、Scannerクラスのnext()メソッドまたはnextLine()メソッドを使用します。
- next()メソッドで文字列を入力します。このメソッドは、空白文字もしくは改行文字が現れるまで入力された文字列を読み取ります。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.next();
System.out.println("输入的字符串是:" + str);
}
}
- nextLine()メソッドを使用して文字列を入力します。このメソッドは、空白や改行文字を含む1行分の文字列を入力します。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
System.out.println("输入的字符串是:" + str);
}
}
next()メソッドとnextLine()メソッドのいずれを使う場合も、ユーザーがどのような種類のデータを入力すればよいかわかるように、文字列を入力する前にプロンプトを出力する必要があります。