java - 如何在while循环中输入整数后的字符串?
问题描述
我正在尝试制作一个程序来计算某人的步数(如果数字大于或等于 10000,程序应该停止),但我似乎找不到输入“回家”然后输入回家所需的步数。
Scanner scan = new Scanner(System.in);
int totalSteps = 0;
while(true)
{
int steps = scan.nextInt();
totalSteps = totalSteps + steps;
if(totalSteps >= 10000) {
System.out.println("Goal reached! Good job!");
break;
}
else if(steps < 10000)
{
String home = scan.nextLine();
if(home.equals("Going home"))
{
int extraSteps = scan.nextInt();
totalSteps = totalSteps + steps + extraSteps;
System.out.println(10000 - totalSteps + " more to reach goal.");
}
}
}
解决方案
你应该看看这个:为什么 nextLine() 返回一个空字符串?
这会起作用:
else if(steps < 10000) {
scan.nextLine();
String home;
while (!(home = scan.nextLine()).isEmpty()) {
if (home.equals("Going home")) {
int extraSteps = scan.nextInt();
totalSteps = totalSteps + steps + extraSteps;
System.out.println(10000 - totalSteps + " more to reach goal.");
}
}
}
推荐阅读
- stripe-payments - 如何检索已连接帐户的 Stripe 会话 ID?
- flutter - 编写此飞镖迭代并返回列表的更好方法是什么
- c++ - 为什么字符数组不给出无符号结果
- c++ - 如何将 dll 库链接到我的应用程序?
- javascript - git 中的路径错误,无法在...处创建目录 无效的参数
- python - 如何将表格值从 Web 表单获取到 post 方法 python 烧瓶中?
- c# - 我在 C# 中的表中插入数据时遇到问题
- scikit-learn - 有没有办法在sklearn中导入train_test_spit?
- python - Pandas - 创建值不同的列
- azure - 与存储帐户的 Azure 分析服务连接不起作用