Scanner类
它提供了输入数据的方法、包含在被称为“实用类”的java.util包中;
在使用前需要创建一个Scanner对象;
声明一个名为in的Scanner变量,并新建一个Scanner对象以便从System.in中获取输入;
🌂:Scanner in = new Scanner(System.in);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package demo1;
import java.util.Scanner;
public class Test_1 {
public static void main(String[] args) { String line; Scanner in = new Scanner(System.in); System.out.print("小黄说:"); line = in.nextLine(); System.out.println("系统检测到小黄说了:"+line); } }
|
在这之间我发现nextline与next都是接收String类型;那它们究竟有什么区别呢?
下面用代码测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package demo1;
import java.util.Scanner;
public class Test_1 {
public static void main(String[] args) { String line; Scanner in = new Scanner(System.in); System.out.print("Type something(nextline):"); line = in.nextLine(); System.out.println("You said:"+line); System.out.print("Type something(next):"); line = in.next(); System.out.println("You said:"+line); } }
|
解释:
next()方法读取到空白符就结束l;
nextLine()读取到回车结束也就是“\r”;