在使用 `Scanner` 类的不同读取方法时,换行符可能会对输入的处理产生影响。

86 阅读2分钟

当我在编写代码时候遇到了一个问题 就是在我输入第一个名字时 他就直接会报出NumberFormatException数字格式异常

image.png

  • 后来才知道原来是因为 前一个的换行符\n 还停留在缓冲区直接导致
  • image.png
  • 这个里面的nextLine 读取到了换行符
  • 转不成int类型 才会报出错误
  • 以下是源代码
public class Demo01 {
    public static void main(String[] args) throws Exception {
        Scanner sc=new Scanner(System.in);
        int age;
        String name;
        while (true){
            try {
                System.out.print("输入学生姓名:");
                name = sc.next();
                System.out.print("输入学生年龄:");
                age = Integer.parseInt(sc.nextLine());


                if(age<18||age>25){
                    throw new IllegalArgumentException("年龄必须在18至25岁之间");
                }
                break;
            } catch (NumberFormatException e) {
                System.out.println("年龄输入无效。请输入一个有效的号码");
            }catch (IllegalArgumentException e){
                System.out.println(e.getMessage());
            }
        }
        Student student=new Student(name,age);
        System.out.println(student);
    }
}

知识点:

  1. 连续使用相同的读取方法(例如两次使用 sc.next()):在这种情况下,第一个 sc.next() 会读取输入直到遇到空格或者换行符,然后第二个 sc.next() 会继续读取输入,即使输入以换行符结束,也会被作为有效输入处理。
  2. 使用不同的读取方法(例如一个 sc.next() 和一个 sc.nextLine()):在这种情况下,如果之前使用了 sc.next() 来读取输入,然后紧接着使用 sc.nextLine(),那么 sc.nextLine() 会读取之前的剩余部分,包括换行符,而不会等待新的输入。这可能导致意外的行为。 如果连续使用相同的读取方法,第二个读取会继续读取输入,不会考虑换行符。
  • 如果使用不同的读取方法,第一个读取方法的换行符可能会影响到第二个读取方法的行为。

还有一种就是直接写int

修改之后:

image.png

public class Demo01 {
    public static void main(String[] args) throws Exception {
        Scanner sc=new Scanner(System.in);
        int age;
        String name;
        while (true){
            try {
                System.out.print("输入学生姓名:");
                name = sc.next();
                System.out.print("输入学生年龄:");
                age = Integer.parseInt(sc.next());

                if(age<18||age>25){
                    throw new IllegalArgumentException("年龄必须在18至25岁之间");
                }
                break;
            } catch (NumberFormatException e) {
                System.out.println("年龄输入无效。请输入一个有效的号码");
            }catch (IllegalArgumentException e){
                System.out.println(e.getMessage());
            }
        }
        Student student=new Student(name,age);
        System.out.println(student);
    }
}