java - 使用 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;
解决方案
调用nextInt()
不会消耗换行符。nextLine()
取而代之的是,在获取导演时,它会被随后的调用消耗掉。为了解决这个问题,您可以改为调用nextLine()
然后Integer.parseInt()
将字符串转换为整数。
推荐阅读
- javascript - TinyMCE 编辑器嵌入 React with Redux Architecture 时,无法更新 React DOM
- python-3.x - 使用 manager.List 打开的文件太多
- java - lambda 中的 Java 8 变量范围(特定于 Spark)
- ios - 自调整 UICollectionView 与 UITableView 与动态标题作为单元格
- javascript - 使用 Jest 模拟更复杂的依赖项 [即基于索引文件的嵌套依赖项]
- ios - 字符串扩展 toDate() 使某些设备崩溃
- javascript - 使用 JavaScript 将变量与嵌套数组中的对象匹配
- react-native - 仅通过 HDMI 反应本机视频
- exception - BobException 怎么了
- javascript - VideoJS 皮肤未在 Firefox 或 Chrome 上显示