System.out.println("请输入您的姓名,然后按Enter。"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { String name = reader.readLine(); System.out.println("Hello, " + name + "!"); } catch(IOException e) { System.out.println("发生错误: " + e.getMessage()); }
此代码需要以下导入:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
System.out.println("Please type your name and press Enter"); Scanner scanner = new Scanner(System.in); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!");
此示例需要以下导入:
import java.util.Scanner;
要读取多行内容,请重复调用:scanner.nextLine()
System.out.println("Please enter your first and your last name, on separate lines."); Scanner scanner = new Scanner(System.in); String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); System.out.println("Hello, " + firstName + " " + lastName + "!");
有两种获取方法Strings,next()和nextLine()。next()返回直到第一个空格的文本(也称为“令牌”),并nextLine()返回用户输入的所有文本,直到按Enter。
Scanner还提供了用于读取除以外的数据类型的实用方法String。这些包括:
scanner.nextByte(); scanner.nextShort(); scanner.nextInt(); scanner.nextLong(); scanner.nextFloat(); scanner.nextDouble(); scanner.nextBigInteger(); scanner.nextBigDecimal();
如果流具有更多请求类型,则将这些方法中的任何一个has作为前缀(如中的)将返回。注意:如果输入的类型不是请求的类型,这些方法将使程序崩溃(例如,为键入“ a” )。您可以使用来防止这种情况(请参阅:异常)hasNextLine()hasNextInt()truenextInt()try {} catch() {}
Scanner scanner = new Scanner(System.in); //创建扫描仪 scanner.useLocale(Locale.US); //设置号码格式除外 System.out.println("Please input a float, decimal separator is ."); if (scanner.hasNextFloat()){ //检查它是否是浮动的 float fValue = scanner.nextFloat(); //直接以float形式获取值 System.out.println(fValue + " is a float"); }else{ String sValue = scanner.next(); //我们无法以浮动形式检索 System.out.println(sValue + " is not a float"); }
String name = System.console().readLine("Please type your name and press Enter%n"); System.out.printf("Hello, %s!", name); //读取密码(不像unix终端那样回显) char[] password = System.console().readPassword();
优点:
读取方法已同步
可以使用格式字符串语法
注意:仅当从真实命令行运行程序而不重定向标准输入和输出流时,这才起作用。从某些IDE(例如Eclipse)中运行该程序时,它不起作用。有关可在IDE中使用并具有流重定向的代码,请参见其他示例。