Java scanner用法
scanner格式:
Scanner sc1 = new Scanner(System.in);
String a = sc1.next();
package com.itheima01;
import java.util.Scanner;//使用Scanner类需要导入对应的包
public class Scanner用法 {
public static void main(String[] args) {
/* 比较next()与nextLine()的区别
*next():
一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格,next()方法会自动将其去掉。
只有输入有效字符后才将其后面输入的空格作为分隔符或者结束符。
(例如:输入hello world,会把有效字符hello后的空格作为结束符,结果只显示hello)
next() 方法不能得到带有空格的字符串。
*nextLine():
以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
可以读取空格。
*/
System.out.println("请输入第一段内容");
Scanner sc1 = new Scanner(System.in); //scanner格式
if(sc1.hasNext()) //判断是否还有输入
{
String a = sc1.next();
System.out.println("输入的内容为"+a);
}
System.out.println("---------------------------------------");
System.out.println("请输入第二段内容");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextLine()) //判断是否还有输入
{
String b = sc2.nextLine();
System.out.println("输入的内容为"+b);
}
/*hasNextInt()的作用--判断输入的是否是整形
类似的还有hasNextByte()、hasNextDouble()等。
*/
System.out.println("---------------------------------------");
System.out.println("请输入第三段内容,输入内容为整形数字");
Scanner sc3 = new Scanner(System.in);
if(sc3.hasNextInt()) //判断输入的是否为数字
{
String c = sc3.nextLine();
System.out.println("输入的内容为"+c);
}else
System.out.println("你输入的有误");
}
}
结果演示:
next():以有效字符后的“ 空格”为结束标记,不能输入带有空格的内容,不然会将有效字符空格之后的内容自动舍弃,只保留空格之前的有效内容。
nextLine():以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符。
hasNextInt():
判断是否是整形,输入的内容不是整形就不执行显示,将跳转到else语句。