关于next()和nextLine()方法的简述…
next()
返回迭代的下一个元素。next()返回输入的字符
1、一定要读取到有效字符后才可以结束输入。
2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
4、next() 不能得到带有空格的字符串。
public class Test {
public static void main(String[] args) {
//从键盘接收数据
Scanner sc = new Scanner(System.in);
System.out.print("以next方式接收:");
//判断是否还有输入
if(sc.hasNext()){
String str1 = sc.next();
System.out.println("输入的数据为:"+str1);
}
sc.close();//关闭输入流
}
}
运行结果:
nextLine():
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白。
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("nextLine方式接收:");
if(sc.hasNextLine()){
String str2 = sc.nextLine();
System.out.println("输入的数据为:"+str2);
}
sc.close();
}
}
运行结果: