英文:
How can I fix my loop to stop when i enter number less than 1 and greater than 50 and to stop when more than 20 inputs?
问题
我需要的代码是,如果用户输入的数字小于1或大于50,则停止运行。到目前为止,我已经编写了以下内容。该循环还进入了无限循环,我希望在输入20次后停止。有任何建议吗?
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences[] = new int[51];
int[] nums = new int[20];
int i = 0;
System.out.println("输入一个数字(1-50):");
nums[i] = reader.readInt();
while (nums[i] >= 1 && nums[i] <= 50) {
i++;
if (i >= 20) {
break; // 增加条件来控制最多输入20次
}
System.out.print("输入一个数字(1-50):");
nums[i] = reader.readInt();
}
注意:由于您要求只返回翻译后的部分,以上是您提供的代码的翻译部分。如果您有关于这段代码的进一步问题或解释,请随时提问。
英文:
I need the code to stop if the user enters a number less than 1 or greater than 50. I have written what is below so far. The loop also goes in an infinite loop and I need it to stop after 20 inputs. Any suggestions?
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences [] = new int [51];
int [] nums = new int[20];
int i=0;
System.out.println("Enter a number (1-50): ");
nums[i] = reader.readInt();
while(nums[i]>= 1 && nums[i]<=50)
{
while(i<19)
{
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
答案1
得分: 1
更改 while(nums[i]>= 1 && nums[i]<=50)
为 while(nums[i]>= 1 && nums[i]<=50 && i<19)
,将 i++
放在循环内部,并移除 while(i<19)
循环。
示例:
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences[] = new int[51];
int[] nums = new int[20];
int i = 0;
System.out.println("输入一个数字 (1-50):");
nums[i] = reader.readInt();
while (nums[i] >= 1 && nums[i] <= 50 && i < 19) {
i++;
System.out.print("输入一个数字 (1-50):");
nums[i] = reader.readInt();
}
英文:
Change while(nums[i]>= 1 && nums[i]<=50)
with while(nums[i]>= 1 && nums[i]<=50 && i<19)
, put i++
inside the loop and remove the while(i<19)
loop.
Sample:
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int occurences [] = new int [51];
int [] nums = new int[20];
int i=0;
System.out.println("Enter a number (1-50): ");
nums[i] = reader.readInt();
while(nums[i]>= 1 && nums[i]<=50 && i<19)
{
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
答案2
得分: 1
你可以像这样编写代码:
while (nums[i] >= 1 && nums[i] < 50 && i < 20) {
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
英文:
you can code like this .
while(nums[i]>= 1&&nums[i]<50&&i<20)
{
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论