gpt4 book ai didi

java - 第一次使用数组,尝试创建频率表

转载 作者:行者123 更新时间:2023-11-29 05:50:09 25 4
gpt4 key购买 nike

我看不出我哪里出了问题,我希望它显示调查结果的频率,但我得到的只是零,例如,如果我输入 1,1,2,2,5我希望它输出:

Displaying response frequencies...
1 2
2 2
3 0
4 0
5 1

但我得到的是:

Displaying response frequencies...
1 0
2 0
3 0
4 0
5 0

这是我的主要方法:

import java.util.Scanner;
public class SurveyTester {

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.println("How many people took the survey?");
int numPeople = input.nextInt();
Survey s = new Survey(numPeople);
int nextResponse;
for (int i = 0; i < numPeople; i++)
{
System.out.print("Input the next survey response (values 1-5):");

nextResponse = input.nextInt();
s.addResponse(nextResponse);
}

System.out.println("Displaying all responses...");
s.displayAllResponses();
System.out.println("Displaying response frequencies...");
s.displayResponseFrequencies();
}

}

这是我的类(class):

public class Survey
{
private int numResponses;
private int maxResponses;
private int[] responses;
private int[] frequencies;
private final int NUM_RESPONSES = 5;

public Survey(int nResponses)
{
maxResponses = nResponses;
numResponses = 0;
responses = new int[nResponses];
frequencies = new int[NUM_RESPONSES]; // There are 5 possible responses to the survey
}

public void addResponse(int response)
{
// This method stores the response
// passed in the parameter 'response'
// to the next free space in the array

{
responses[numResponses]= response;
}

numResponses++;
}


public void displayAllResponses()
{
// This method displays on the screen
// all the responses to the survey

for (int i=0; i<maxResponses; i++)
{
System.out.print(responses[i] + " ");
}

System.out.println("");
}


public void calculateResponseFrequencies()
{
// This method calculates the number of
// responses for each possible answer
// to the survey, 1, 2, 3, 4 or 5
// It stores the frequencies in the
// array 'frequencies'

for (int i=1; i<=maxResponses; i++)
{
if (responses[i] == 1)
{
frequencies[1]++;
}

else if (responses[i] == 2)
{
frequencies[2]++;
}

else if (responses[i] == 3)
{
frequencies[3]++;
}

else if (responses[i] == 4)
{
frequencies[4]++;
}

else if (responses[i] == 5)
{
frequencies[5]++;
}
}
}

public void displayResponseFrequencies()
{
// This method displays the response
// frequences for each of the possible
// response, 1, 2, 3, 4 or 5

for (int i=0; i<frequencies.length; i++)
{
System.out.println((i+1) + "\t" + frequencies[i]);
}
}

}

最佳答案

您没有对frequencies 数组做任何事情。在您的 addResponse 方法中,您需要获取适当的值并递增它。添加如下语句

频率[response-1] = 频率[response-1] + 1;

请注意,您可以像现在一样使用 2 个数组来执行此操作,尤其是对于学习而言,但是许多 Java 开发人员会使用 Map 实现来处理此类事情,其中​​键是输入的值和值是频率。将所有数据保存在一个数据结构中。

关于java - 第一次使用数组,尝试创建频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224879/

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