gpt4 book ai didi

java - 如何限制数组中的打印次数?

转载 作者:行者123 更新时间:2023-12-02 05:20:20 24 4
gpt4 key购买 nike

非常接近让这个程序工作,但我被困住了。我想要它做的只是打印出实际出现的数字,所以如果用户输入:1,2,3,2,6

需要显示

1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times

我使用相同的输入实际上得到的是这样的:

1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times
5 - 0 times
6 - 1 times

我需要删除没有发生的情况。

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

//Create Array for numbers
int numbers[] = new int[100];

//Prompt user input
System.out.println("Enter integers between 1 and 100: ");
//For loop to continue input
for (int i = 0; i < numbers.length; i++) {
int next = input.nextInt();
//Breaks loop if 0 is inputted
if (next==0)
{
break;
}
numbers[i] = next;
}

//Calls on countInts method
int[] count = countInts(numbers);
//Calls on display counts
displayIntCount(count);

}

//Counts each instance of a integer
public static int[] countInts(int[] ints)
{
int[] counts = new int[100];

for(int i = 1; i <=counts.length; i++)
for(int j=0;j<ints.length;j++)

if(ints[j] == i)
counts[i-1]++;
return counts;
}

//Displays counts of each integer
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++)
System.out.println((i+1) +" - " +counts[i] +" Times");
}
}

最佳答案

只需使用一个简单的 if 语句来检查 counts[i] 是否不为 0,如下所示:

public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((i+1) +" - " +counts[i] + " Times");
}
}
}

关于java - 如何限制数组中的打印次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566173/

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