//有没有更好的方法来显示返回的信息,而不必写我在S.O.p中写的所有内容。目标是返回值,然后将其链接到参赛者的姓名和时间。谢谢你的帮助。//
public class array_Test
{
public static void main(String args[])
{
String[] names={"Bob", "Tj", "Aj"};
double [] times={9.9,9.8,10.0};
double x=findLargest(times);
System.out.print("The slowest racer was " + names[1] + " with a time of "
+ times[1] + " at index position" + x);
}
public static double findLargest(double[] times)
{
int indexOfLargest=0;
double largest=times[0];
for(int i=0; i<times.length; i++)
{
if(times[i]>largest)
{
largest=times[i];
indexOfLargest=i;
}
}
return indexOfLargest;
}}
为什么不使用类?你可以将参赛者的姓名和时间与以下内容合并:
public class Racer {
private String name;
private double time;
private int position;
public Person(String name, double time){
this.name = name;
this.time = time;
this.position =-1;
}
public String getName() {
return name;
}
public double getTime() {
return time;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position
}
@Override
public String toString() {
return "The slowest racer was " + getName + " with a time of "
+ getTime + " at index position" + getPosition);
}
}
这个类允许您管理easlier您的"Racer"和函数toString()的覆盖允许您自定义printl()。
您现在可以更改您的代码:
public class array_Test
{
public static void main(String args[])
{
Racer[] people ={new Person("Bob",9.9),new Person("Tj",9.8),new Person("Aj",10.0)};
double x=findLargest(times);
System.out.print(Racer[x].toString());
}
public static double findLargest(double[] times)
{
int indexOfLargest=0;
double largest=people[0].getTime();
for(int i=0; i<people.length; i++)
{
if(people[i].getTime()>largest)
{
largest=people[i].getTime();
indexOfLargest=i;
}
}
people[indexOfLargest].setPosition(indexOfLargest);
return indexOfLargest;
}}