首页 > 解决方案 > 使用 Scanner 函数获取用户输入

问题描述

所以我试图使用扫描仪类来接收来自用户的一些不同的输入。他们可以输入电影名称、年份、导演、时长、演员和类型。

但是,对于其中一个用户输入,它将导演和持续时间一起打印。

这是一个屏幕截图以供更多参考。为什么同时要求用户输入导演和持续时间,但期望用户输入持续时间?

代码和输出

    System.out.println("Enter the title: ");
    String title = myObj.nextLine();

    System.out.println("Enter the year: ");
    int year = myObj.nextInt();

    System.out.println("Enter the duration: ");
    int duration = myObj.nextInt();

    System.out.println("Enter the director: ");
    String director = myObj.nextLine();

    System.out.println("Enter the actors: ");
    String actors  = myObj.nextLine();
    
    System.out.println("Enter the genre: ");
    String genre = myObj.nextLine();
    int rating = ran.nextInt(10) + 1;

标签: javajava.util.scanneruser-input

解决方案


调用nextInt()不会消耗换行符。nextLine()取而代之的是,在获取导演时,它会被随后的调用消耗掉。为了解决这个问题,您可以改为调用nextLine()然后Integer.parseInt()将字符串转换为整数。


推荐阅读