一:导入Scanner包
Scanner类定义在java.util包中。
import java.util.Scanner;
二:构造Scanner对象
要想通过控制台进行输入,需要构造一个Scanner对象,并与“标准输入流”System.in关联。
Scanner in = new Scanner(System.in);
1、nextLine方法将输入一行(使用nextLine方法是因为在输入行中可能包含空格)
System.out.println("what is your name?");
String name = in.nextLine();
2、要想读取一个单词(以空白作为分隔符),就调用
String firstName = in.next();
3、要想读取一个整数,就调用nextInt方法。
System.out.print("How old are you ?");
int age = in.nextInt();
注意:
如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:"\r\n",因为nextInt仅仅读取数字信息,而不会读取回车换行"\r\n".
所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串
4、与此类似,要想读取下一个浮点数,就调用nextDouble方法。
三:注意密码的输入
因为输入是可见的,所以Scanner类不适用于从控制台读取密码。Java SE 6 特别引入了Console类实现这个目的。
5、要读取一个密码,可以采用下列代码:
Console cons = System.console();
String username = cons.readLine("User name:");
char[] passwd = cons.readPassword("Password:");
函数说明:
static char[] readPassword(String prompt, Object ... args)
static String readLine(String prompt, Object ... args)
显示字符串prompt并且读取用户输入,直到输入行结束。