注意:windows平台的换行符为\r\n ; linux平台的换行符为\n;
\r 表示回车 Carriage Return ; \n 表示新行 New Line
Scanner接收字符串的方法:
1.next(); (next()、nextInt()、nextFloat()等等)一定要读取到有效字符之后才会结束输入,有效字符之前遇到的空格、Tab键或Enter(\r\n)键等结束符会自动将其去掉,.有效字符之后遇到的Enter键才将其视为结束符,所以next()方法不能得到带空格的字符串。结束读取后,光标不移动到下一行
2.nextLine() 读取包括空格在内的输入,而且还会读取行尾的换行字符\n,读取完成后光标被放在下一行
System.out.println("請輸入學生的ID");
Scanner sc = new Scanner(System.in);
String sid = sc.nextLine();
System.out.println("請輸入學生的姓名");
String name = sc.nextLine();
System.out.println("請輸入學生的年齡");
String age = sc.nextLine();
System.out.println("請輸入學生的性別");
String sex = sc.nextLine();
Student s = new Student(sid, name, age, sex);
arr.add(s);
如果不是使用nextLIne(而使用next()),则有可能导致数据丢失,因为你多读取了\r
ps :可以只生成一个Scanner对象而多次接收控制台输入的信息