java中next 、hasNext,nextLine、hasNextLine的区别

、、、
Scanner sc = new Scanner(System.in)
、、、

通过Scanner 类的next()和nextLine()方法获取收入的字符串,在读取之前一般需要用hasNext与hasNextLine判断是否还有输入的数据

next方法

、、、
import java.util.Scanner;

public class ScannerDemo {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//从键盘输入数据

    //next方式接收字符串
    System.out.println("next method receive data");
   //判断是否还有输入
    if(sc.hasNext()){
        String str1 = sc.next();
        System.out.println("input data:"+str1);
    }
    sc.close();
}

}
、、、

nextLine方法

、、、
public class ScannerDemo {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//从键盘输入数据

    //next方式接收字符串
    System.out.println("nextLine method receive data");
   //判断是否还有输入
    if(sc.hasNextLine()){
        String str1 = sc.nextLine();
        System.out.println("input data:"+str1);
    }
    sc.close();
}

}
、、、

next和nextLine的区别
next
1.一定会读取到有效字符才可以结束
2.对输入有效字符之前遇到的空白,next方法会自动将其去掉
3.只有输入有效字符后才将后面输入的空白作为分隔符或者结束符号
4.next()不能得到带有空格的字符串
nextline()
1.以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
2.可以获得空白

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容