美文网首页
nextLine()和next()、nextInt()等类型的区

nextLine()和next()、nextInt()等类型的区

作者: 教堂白鸽 | 来源:发表于2018-11-07 23:01 被阅读0次

    nextLine()只以Enter键作为结束,即可以读取有效字符和无效字符(Tab、空格)。
    next()只能读取有效字符,即Tab,空格,Enter均是它的结束符。(nextInt()、nextDouble()等类同)。

    
    import java.util.Scanner;
    
    /**
     * Created by AlexanderBai on 2018/11/7.
     */
    public class Demo {
    
        public static void main(String[] args) {
            Scanner scanner=new Scanner(System.in);
            System.out.print("输入第一个字符串:");
            String string1=scanner.next();//nextInt()、nextDouble()、nextBoolean()用法雷同
            System.out.print("第一个字符串是:");
            System.out.println(string1);
    
            System.out.print("输入第二个字符:");
            String string2=scanner.nextLine();
            System.out.print("第二个字符串是:");
            System.out.println(string2);
        }
    }
    

    运行结果:


    image.png

    由于next()只能读取有效字符(遇到第一个无效字符时结束),所以无法输入第二个字符;
    nextLine()读取输入流中的剩余字符作为自己的字符串返回
    解决方法是在连用之间增加一个 scanner.nextLine()


    next()、nextInt()等类型连用方法

    package com.bbg.personinfo;
    
    import java.util.Scanner;
    
    /**
     * Created by AlexanderBai on 2018/11/7.
     */
    public class Demo {
    
        public static void main(String[] args) {
            Scanner scanner=new Scanner(System.in);
            System.out.print("输入第一个字符串:");
            String string1=scanner.next();//nextInt()、nextDouble()、nextBoolean()用法雷
    
            scanner.nextLine();//在连用之间增加一个 scanner.nextLine()
    
            System.out.print("第一个字符串是:");
            System.out.println(string1);
    
            System.out.print("输入第二个字符:");
            String string2=scanner.nextLine();
            System.out.print("第二个字符是:");
            System.out.println(string2);
        }
    }
    

    运行结果


    image.png

    相关文章

      网友评论

          本文标题:nextLine()和next()、nextInt()等类型的区

          本文链接:https://www.haomeiwen.com/subject/pzybxqtx.html