public class Elections1 {
public static int visit(String[] likelihoods){
double smallestPer=1.00;
int smallestIndex=0;
//Go through each element inside likelihoods
for(int i=0;i<likelihoods.length;i++){
String likelihood = likelihoods[i];
// Calculate the percentage
int countOfOne = 0;
//What to include here???
double percentage = (double)countOfOne/likelihood.length();
//Store the smallest value by comparing the smallest percentage
if(percentage < smallestPer){
smallestPer = percentage;
smallestIndex = i;
}
}
//Return the index number
return smallestIndex;
}
public static void main(String[] args) {
String[] likelihood={"1222","1122","1222"};
System.out.println(visit(likelihood));
}
}
我需要返回喜欢中最小百分比的索引号,我可以在&#34;计算百分比&#34;中包含哪些陈述。对于每个possibles.length?
答案 0 :(得分:0)
如果你希望函数只是在数组中找到最小的百分比,并且数组由字符串形式的百分比组成,那么你可以将字符串解析为整数并进行比较。
假设您希望1222,1122和1222分别为12.22%,11.22%和12.22%,那么将字符串解析为整数并进行比较就足够了。
话虽如此,您不需要声明实际声明的许多变量。
public class Percentages {
public static int visit(String[] likelihoods) {
int smallestPer = Integer.MAX_VALUE;
int smallestIndex = 0;
//Go through each element inside likelihoods
for (int i = 0; i < likelihoods.length; i++) {
int likelihood = Integer.parseInt(likelihoods[i]);
//Store the smallest value by comparing the smallest percentage
if (likelihood < smallestPer) {
smallestPer = likelihood;
smallestIndex = i;
}
if (likelihood == 0) {
return i;
}
}
return smallestIndex;
}
public static void main(String[] args) {
String[] likelihood = {"1222","1122","1222"};
System.out.println(visit(likelihood));
}
}
这对我有用。这是你想要的吗?