java - 错误更新变量
问题描述
我想更新我的变量,我的代码有一个错误,我不知道哪里有错误
String name = " ";
String family = " ";
int age = 0;
Scanner input = new Scanner(System.in);
int choise;
while (true){
System.out.println("1:Name 2:Family 3:Age ---- 0:Exit");
choise = input.nextInt();
if (choise == 0) break;
else if (choise == 1){
System.out.println("Please enter the name : ");
name = input.nextLine();
}
else if (choise == 2){
System.out.println("Please enter the family : ");
family = input.nextLine();
}
else if (choise == 3){
System.out.println("Please enter the age : ");
}
}
解决方案
我试图在本地运行您的代码,但在那里发现了 2 个问题:
- 与第 1 项相关,根据结果,应用程序应等待输入名称。在我输入我的名字后,它抛出了一个错误。为什么?显然,应用程序不是等待名称,而是选择。
问题在这里清楚地描述: Java Scanner doesn't wait for user input
问题是 nextInt() 不消耗 '\n',所以下一次调用 nextLine() 消耗它,然后它正在等待读取 y 的输入
我的建议是更改nextInt()
为nextLine()
然后手动转换为 int
choise = Integer.parseInt(input.nextLine());
推荐阅读
- google-apps-script - 使用驱动器中的第三方库和谷歌工作区中的文档设置需要将哪个域列入工作表插件的白名单?
- android - android adb shell 中的“错误=2,没有这样的文件或目录”错误
- python - 找到带有“变量”的跨度标签?但没有课 - 美丽的汤/Python
- python - python fifo阻止写入直到读取
- image - 当我在手机中构建和启动 apk 时,为什么我的“黑色”编辑文本颜色变为“白色”?
- storybook - 如何用不同的装饰器展示两个故事?
- geofence - 我可以根据设备的位置为其他设备添加地理围栏吗?
- php - 从 Laravel 8.x 中移除前端脚手架
- laravel - 使用wire:click或alpine js设置wire:model值?
- javascript - JavaScript 多元素对象移动