gpt4 book ai didi

java - 返回整数数组中最大的数

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:12 24 4
gpt4 key购买 nike

我试图让我的程序打印整数数组中的最大值。cVoteA 是特定候选人 (cNameA) 的票数。cVoteA 和 cNameA 的值是使用 GUI.getInt 手动输入的

每次运行该程序时,它只会打印名字,但我不知道如何让它打印最大的名字。

//WinnerM value method
public static String WinnerM(String cNameA[], int cVoteA[], int thresh, int winner)
{
int total = cVoteA[0]; //Declare the total variable and set it to 0
int iv = 0;
for (iv = 0; iv < cVoteA.length; iv++)
{
if(cVoteA[iv] > total)
{
winner = cVoteA[iv];
}
}
return cNameA[winner]; //Return candidate name
}

这里是调用该方法的地方

//FIND WINNER
int winner = 0;
WinnerM(cNameA, cVoteA, thresh, winner);

System.out.println("Winner " + " " + cNameA[winner]); //Print Winner and the name of the candidate with most votes

感谢任何帮助

通过 BlueJ 使用 Java 语言

最佳答案

  1. 将 cVotaA(winner)最大位置的变量初始化为第一个数组元素。
  2. cVoteA(iv) 与迄今为止的最大 cVoteA cVoteA(winner) 进行比较。
  3. 找到新的最大值后,将下标 (iv) 保存到winner
  4. 使用最大值(winner)的下标输出值和名称。

关于java - 返回整数数组中最大的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389159/

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