我正在尝试做的是搜索“gradePsd”数组找到最高等级,如果有两个等级相同的值,则打印学生的名字以便控制台。
我遇到的问题是这个方法是获取数组的第一个索引值并打印它,因为它是第一遍的高值,如果第二个值大于第一个,那么它也将打印等等。
所以我的问题是如何才能让它打印出高分的学生。
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
for (int i = 0; i < gradePsd.length; i++)
{
if (gradePsd[i] >= num)
{
num = gradePsd[i];
nameRtn = NamePsd[i];
}
System.out.print(nameRtn + ", ");
}
}
答案 0 :(得分:0)
使用-1初始化num
并从for循环中取出System.out
。但是你只能用你的代码确定一个学生。如果您想存储多个名称,则需要nameRtn
为Collection
。
这样的事情:
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
Collection<String> namesRtn = new ArrayList<String>();
int num = -1;
for (int i = 0; i < gradePsd.length; i++) {
if (gradePsd[i] > num) {
num = gradePsd[i];
namesRtn.clear(); // clear name list as we have a new highest grade
namesRtn.add(NamePsd[i]); // store name in list
} else if (gradePsd[i] == num) {
namesRtn.add(NamePsd[i]); // if a second student has the same grade store it to the list
}
}
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
}
答案 1 :(得分:0)
首先找到最高的数字 然后用那个号码打印学生
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
//find the highest number
for (int i = 0; i < gradePsd.length; i++){
if (gradePsd[i] >= num){
num = gradePsd[i];
}
//print students with that number
for (int j = 0; j < NamePsd.length; j++){
if (gradePsd[j] == num)
{
nameRtn = NamePsd[j];
System.out.print(nameRtn + ", ");
}
}
可能的1000种解决方案之一。