Scanner对象
java.util.Scanner是java5的新特征 ,可以用scanner类是用来获取用户的输入
基本语法
Scanner s=new Scanner(System.in);
通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。
next();
1,一定要读取到有效的字符后才可以结束输入
2,只对输入的有效字符之前遇到的空白(就是空格)next()方法会自动将其去掉
3,只有输入有效字符后才将其后的空白作为分隔符或者结束符
4,next()不能得到带有空格的字符串。
这是用next()方法接收参数
``
public class Demo {
public static void main(String[] args) {
//创建一个烧苗其对象,用来接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("用next方法接收");
if (scanner.hasNext()){
String str=scanner.next();
System.out.println("输入的字符串为:"+str);
}
//凡是io流不关闭都会占用资源,要养成良好的习惯,用完就关掉。
scanner.close();
}
}
输入结果:
分析:我输入了hello world 但是只输出了hello ,是因为在hello后面有空格,所有空格被当成结束符,无法输出带有空格的字符串。
nextLine();
1,以enter为结束符,也就是说nextline()方法返回的是输入回车之前的所有字符,
2,可以获得空白
用nextLine()方法接收参数:
``
public class Demo1 {
public static void main(String[] args) {
//接收键盘输入
Scanner scanner = new Scanner(System.in);
System.out.println("用hasnextLine接收数据");
//判断用户是否有输入
if (scanner.hasNextLine()){
String str =scanner.nextLine();
System.out.println("用nextLine方法接收:"+str);
}
scanner.close();
}
}
输入结果:
分析:可以完整的输出带有空格的字符串