java如何使用标志变量来结束用户的输入
我有一个整数数组列表,它将由用户填充,我想在用户需要之前接受输入。我该怎么做
我已经试过了,但没有让我满意。其中s是用户的最终令牌
for(int i=0;input.nextInt()!='s';i++)
{ int a=input.nextInt();
number.add(a);
}
你可以在下面搜索框中键入要查询的问题!
我有一个整数数组列表,它将由用户填充,我想在用户需要之前接受输入。我该怎么做
我已经试过了,但没有让我满意。其中s是用户的最终令牌
for(int i=0;input.nextInt()!='s';i++)
{ int a=input.nextInt();
number.add(a);
}
# 1 楼答案
使用
nextInt()
不会解决您的问题,因为一旦用户输入非整数,它将生成异常,因此您的循环条件将永远不会执行。此外,您应该只使用while
循环,而不是使用for
循环,因为您的迭代计数未知。我已经修改了你的代码。请参阅下面的代码和代码注释# 2 楼答案
您可以使用正则表达式来解析传递的输入,解决方案将排除浮点和字符串
输入
输出