一、Scanner功能
1.实现程序与人的交互;
2.通过Scanner类获取用户的输入;
(个人理解:和c语言中的sanf函数差不多)
基本语法
Scanner scanner = new Scanner(System.in);
在使用上,通过Scanner类的 next() 或 nextLine() 方法获取输入的字符串。
使用Scanner类的 hasnext() 或 hasnextLine() 方法判断是否还 有输入的字符串。
- next()
package com.scnner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);//创建一个扫描器,接受键盘数据;
System.out.println("使用next 方法接收:");
if(scanner.hasNext())//判断用户有无输入字符串;
{
String str=scanner.next();//使用next方式接收;
System.out.println("输出的内容为:"+str);//输出;
}
scanner.close();//凡属于IO流的如果不关闭就会一直占用资源,要用完就关掉;
}
}
- nextLine()
package com.scnner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine接收:");
if(scanner.hasNextLine())
{
String str=scanner.nextLine();
System.out.println("输出的内容为:"+str);
}
scanner.close();
}
}
这两种的区别我们可以输入字符串进行区别;
总结
next()
- 一定要读取到有效字符后才可以结束输入。
- 对输入有效字符之前遇到的空白next()方法会自动将其去除。
- 只有输入有效字符后才将后面输入的空白作为分隔符或者结束符。
- next()不能带有空格的字符串。
nextLine()
- 以Enter为结束符,也就是说nextLine()返回输入回车之前的所有字符。
- 可以获得空白。