Java简单程序编写,超级感谢啊(返回数组元素中的最大值的下标)

2025-03-04 12:18:54
推荐回答(3个)
回答1:

public static int max(Comparable[] table) {
if(table.length==0){
return -1;
}else{
int temp = 0;
Comparable c = table[0];
for(int i=1;i if(table[i].compareTo(table[temp])>0){
temp = i;
}
}
return temp;
}
}
==============================================================
测试主函数
public static void main(String[] args){
Integer[] i ={1,2,3,5,47,9,};
System.out.println("最大下标:"+max(i));
}
================================================================
测试结果:
最大下标:4

回答2:

楼主看看我刚写的! 你可以照着改下:
//求整数组中的最大和最小值!
public class bb
{ public static void main(String[] args)
{
int str[]={1,32,4,7,4,9,33,56,43,-7};
int max=0;
int min=0;
max=str[0];
min=str[0];
for(int i=0;i {
if(str[i]>max)
{
max=str[i];
}
if(str[i] {
min=str[i];
}
}
System.out.println("最大值为:"+max);
System.out.println("最小值为:"+min);
}
}

回答3:

public class Test3 {
public static void main(String[] args) {
User[] users = new User[] {
new User("1005", 50),
new User("1002", 60),
new User("1003", 101) };
max(users);

}

public static void max(Comparable table[]) {
//如果作为单独的方法,此处还需判断传入的参数合法性
Arrays.sort(table);//按值排序
System.out.println(((User)table[table.length-1]).getId());//排序后最后面那个

}

static class User implements Comparable {

private int age;
private String id;

public User(String id, int age) {
this.id = id;
this.age = age;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Override
public int compareTo(Object o) {
return this.age - ((User) o).getAge();

}

}

}