zoukankan      html  css  js  c++  java
  • Scanner中关于next()、nextInt()和nextLine()的问题

    实例:

    	Scanner input = new Scanner(System.in);
            System.out.println("请输入数字:");
            int option = input.nextInt();//read numerical value from input;
            System.out.println(option);
            System.out.println("请输入字符串1:");
            String string1 = input.nextLine();//read 1st string (this is skipped)
            System.out.println("请输入字符串2:");
            System.out.println(string1);
            String string2 = input.nextLine();//read 2nd string (this appears right after reading numerical value)
            System.out.println(string2);
    

    out:

    请输入数字:
    5 
    5
    请输入字符串1:
    请输入字符串2:
     
    22
    22
    

    通过上面的实例可以发现:这种交叉输入的时候Scanner读取会出现问题。

    原因:

    接下来我把我从大牛那里理解的原因分享一下:

    注释:(英语不行凑合着看)

    nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

    只读取整数类型数据, nextInt()在读取完输入后把光标放在读取数据的同一行,该数据的后面。

    next(): read the input only till the space. It can't read two words separated by space. Also, next() places thecursor in the same line after reading the input.

    只读取到空格,不能读取被空格分开的两个单词(也就是不能读取空格),并且在读取完后把光标放在读取数据的同一行,该数据的后面。(同上)

    nextLine(): reads input including space between the words (that is, it reads till the end of line ). Once the input is read, nextLine() positions thecursor in the next line.

    读取整行的数据包括单词间的空格,到回车结束(也就是从开始读一整行包括回车),读取结束后,光标放在下一行开头。

    所以上面一题的原因:nextInt()只读取了数值2,剩下" "还没有读取,并将光标放在本行中2后面。接着nextLine()会读取" ",并结束本次读取

    注意:回车表示一行输入结束。

    解决方法:

    1、在交叉使用时可以用next()代替nextLine();

    2、可以在nextInt()(或next())和nextLine()之间添加一个nextLine()用来吸收掉空格或回车;

    3、其他。

    例子:

    		Scanner in = new Scanner(System.in);
    		//输入并输出一个整数
    		int n = in.nextInt();
    		System.out.println(n);
    		
    		in.nextLine();//添加nextLine吸收回车
    		//输入并输出一个字符串
    		String String1 = in.nextLine();
    		System.out.println(String1);
    		
    		//输入并输出一个字符串
    		String s = in.next();
    		System.out.println(s);
    		
    		//输入并输出一个字符串
    		String String2 = in.next();//改用next()
    		System.out.println(String2);
    

    out:

    2
    2
     dkh//字符串前面输入空格
     dkh
     abc//字符串前面输入空格
    abc
    bda
    bda
    
    
  • 相关阅读:
    练习题
    练习题
    作业 —— day77
    解决:Django项目no such table django_session
    解决:A server error occurred. Please contact the administrator
    作业24
    元类
    类的内置方法
    反射
    考试错题
  • 原文地址:https://www.cnblogs.com/zx-coder/p/12799524.html
Copyright © 2011-2022 走看看