Scanner中的bug

2019-10-03  本文已影响0人  聪明的小一休

Scanner中先读取String,再读取int,一切都正常。
但反过来,就会出现bug。


字符流

nextInt会不断读取字符,直到遇到非数字字符。
nextInt返回10后,调用nextLine,这个方法会不断读取字符,直到遇到换行符,但下一个就是换行符,所以会返回空字符串。

package params3;
import java.util.Scanner;
public class Test1 {
    //Scanner中的bug
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入整数:");
        int a=sc.nextInt();
        sc.nextLine();//读取独占一行的int/double时,需要符读取换行,否则字符串读取时会直接遇到int/double后的“\n”,输出空字符串
//      System.out.println();// 这样换行不可以
        System.out.println("请输入字符串:");
        String b=sc.nextLine();
        System.out.printf("%d是整数,%s是字符串",a,b);
        System.out.println();
        System.out.printf("%s是字符串,%d是整数",b,a);  
    }
}
添加sc.nextLine(); 不添加sc.nextLine();
上一篇 下一篇

猜你喜欢

热点阅读