纠正 nextLine() 行为
第二个代码示例中使用 nextLine() 时遇到的问题源于 nextInt() 的组合和 nextLine().
问题nextInt()
nextLine() 消耗整行,包括空格和按 Enter 键之前输入的字符。但是,nextInt() 仅消耗数值。如果数字后面有非数字字符或空格,nextLine() 将尝试读取它们,从而导致意外行为。
解决方案:消耗剩余换行符
以确保nextLine() 按预期读取完整行,您可以在每个 nextInt() 之后添加一个 nextLine() 调用以消耗该行上的任何剩余字符。这确保了当使用 nextLine() 读取句子时,它将收到完整的一行。
更正示例:
// Example #2 (Corrected) import java.util.Scanner; class Test { public void menu() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nMenu Options\n"); System.out.println("(1) - do this"); System.out.println("(2) - quit"); System.out.print("Please enter your selection:\t"); int selection = scanner.nextInt(); scanner.nextLine(); // Consume remaining newline if (selection == 1) { System.out.print("Enter a sentence:\t"); String sentence = scanner.nextLine(); System.out.print("Enter an index:\t"); int index = scanner.nextInt(); System.out.println("\nYour sentence:\t" + sentence); System.out.println("Your index:\t" + index); } else if (selection == 2) { break; } } } }
以上是为什么 `nextLine()` 在 `nextInt()` 之后会出现错误行为以及如何修复?的详细内容。更多信息请关注PHP中文网其他相关文章!
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前By尊渡假赌尊渡假赌尊渡假赌
刺客信条阴影:贝壳谜语解决方案
3 周前ByDDD
Windows 11 KB5054979中的新功能以及如何解决更新问题
2 周前ByDDD
威尔R.E.P.O.有交叉游戏吗?
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6
视觉化网页开发工具

WebStorm Mac版
好用的JavaScript开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

记事本++7.3.1
好用且免费的代码编辑器