gpt4 book ai didi

java - 使用 while 循环与数组中的值进行比较

转载 作者:行者123 更新时间:2023-12-01 09:57:07 26 4
gpt4 key购买 nike

我需要程序循环运行,直到输入 0。我的代码将以输入 0 结束,但是当尝试运行输入数字的程序时,它仍然会结束程序。而不是运行输入的数字。 while循环的作用是让程序保持运行,除非输入0。

import java.util.Scanner;
public class CountCompare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter the integers between 1 and 100 (0 to end, 0 < to exit): ");
int[] counts = new int[100];
// Count occurrence of numbers
count(counts);

while(counts[0] > 0){
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.println((i + 1) + " occurs " + counts[i] +
" time" + (counts[i] > 1 ? "s" : ""));
}
System.out.print("Enter the integers between 1 and 100 : ");

// Count occurrence of numbers
count(counts);
}
System.out.print("\nEnd of run");
}

/** Method count reads integers between 1 and 100
* and counts the occurrences of each */
public static void count(int[] counts){
Scanner input = new Scanner(System.in);
int num; // holds user input
do {
num = input.nextInt();
if (num >= 1 && num <= 100)
counts[num - 1]++;
} while (num != 0);
}
}

I have posted the entire program.

输出看起来像这样

输入 1 到 100 之间的整数(0 结束,<0 退出):23 23 4 5 6 7 804 出现 1 次5 出现 1 次6 出现 1 次7 出现 1 次8 出现 1 次23 出现 2 次

输入 1 到 100 之间的整数:

最佳答案

你的程序仍然结束,因为:

int[] counts = new int[100];

您已在此处定义了计数限制。这意味着你的循环将运行

for (int i = 0; i < counts.length; i++)// counts.length=100;

因此,就您的代码而言,您希望在用户输入 0 时结束用户输入。因此您可以这样做:

int x=1;
int y;
Scanner sc= new Scanner(System.in);
while(x!=0){
System.out.println("Enter your values");
y=sc.nextInt();
if(y==0){
x=0;
}
else{
System.out.println("You entered "+y);
}

关于java - 使用 while 循环与数组中的值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37106897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com