所有读过这篇文章的人,大家好,
我仍在学习 Java,但我不知道如何将另一个类的结果放入主类的数组中,然后编写一个方法来比较数组中的某些结果。
情况如下:
- 我有一个 App.java,其中包含主要方法
- 我使用 Car.java,其中包含随机汽车的字段、获取/设置和方法
- 我使用构造函数从 Car.java 获取结果并打印它们。
- 我希望将 Car.java 给出的所有结果放入 App.java
中的数组中
- 然后,一个方法将读取该数组并检查 Car.java 中哪辆车具有最高的最大速度,并相应地显示它。
public class App
{
public static void main(String[] args)
{
/**************constructor**************/
Auto a = new Auto("AB-01-CD",3,"black","Opel",260,"Astra",2007,5);
Auto b = new Auto("EF-23-GH",5,"Green","Opel",200,"Corsa",2002,3);
Auto c = new Auto("IJ-45-KL",2,"Red","Ferrari",415,"F1",2010,7);
a.print();
b.print();
c.print();
/******here should the results of Auto "a" "b" and "c" be put in an array*****/
array[] = a, b, c;
/*******and here it should print the highest speed of the cars that are in the array*****/
speed(array[]).print();
}
public int speed(int s)
{
/***********some kind of method that calculates the car with the highest speed******/
return s;
}
}
提前非常感谢您!
亲切的问候,SteelDevil
编辑:
将此添加到 App.java 的主方法
public void main
{
Auto[] array = new Auto[] {a, b, c};
System.out.println("The car with the highest speed is: ");
int maxSpeed = getHighestSpeed(array);
System.out.println(maxSpeed);
}
在App.java中添加了新方法
public int getHighestSpeed (Auto[] array)
{
int highest = 0;
for (Auto auto : array)
{
if (auto.getSpeed() > highest)
{
highest = auto.getSpeed();
}
}
return highest;
}
在编译器处获取错误代码:
App.java:25: 错误:无法从静态上下文引用非静态方法 getHighestSpeed(Auto[])
int maxSpeed = getHighestSpeed(array);
1 个错误
最佳答案
从设计角度(我认为总体而言)正确的方法是创建 Car
的 List
并使用它们的 getter 方法(getSpeed
-方法应由Car
-类提供)。
示例:
Auto a = new Auto("AB-01-CD",3,"black","Opel",260,"Astra",2007,5);
Auto b = new Auto("EF-23-GH",5,"Green","Opel",200,"Corsa",2002,3);
Auto c = new Auto("IJ-45-KL",2,"Red","Ferrari",415,"F1",2010,7);
List<Auto> autos = new ArrayList<>();
autos.add(a);
autos.add(b);
autos.add(c);
int getMaxSpeed(List<Auto> list) {
int maxSpeed = 0;
for(Auto act : list) {
if(act.getSpeed() > maxSpeed)
maxSpeed = act.getSpeed();
}
return maxSpeed;
}
int maxSpeed = getMaxSpeed(autos);
顺便说一句,如果您在问题中编写 Car
并在代码中编写 Auto
,这可能会让非德国人感到非常困惑;)
编辑:您还可以为您的 Car
类编写一个 Comparator
,但这对于这样一个小问题来说有点太多了,只是提到它存在并且有很多舒适的函数可以进行比较,例如使用 Comparator 获得最大值
关于java - 在 Java 中需要一些有关数组构造函数和比较数组结果的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20286349/