Reputation: 295
I got a question about how to return values when the method invoked in main method, here is my partial code:
import java.util.ArrayList;
public class Race {
private ArrayList<Car>cars;
public Race(){
cars=new ArrayList<Car>();
}
public Car find(double position){
for(Car d:cars){
if(d.getPosition()==position){
return d;
}
}
return null;
}
.................
When I called the find method in main class:
public class Test {
public static void main(String[] args) {
Race race=new Race();
Car mazda=new Car("Mazda",1.0,1.0,2.0,2.0);
Car honda=new Car("Honda",1.0,1.0,1.0,2.0);
race.addCars(mazda);
race.addCars(honda);
System.out.println(race.find(1.0).getName());
The third values are position, which means mazda and honda have the same position and it is supposed to print both, but when I run it, it only prints mazda, I am confused, please advise, cheers!
Upvotes: 0
Views: 5888
Reputation: 16987
You can only return one value from a method. But you can return a List
:
public List<Car> find(double position) {
List<Car> ret = new ArrayList<Car>();
for (Car c : cars)
if (c.getPosition() == position)
ret.add(c);
return ret;
}
If this is all you do, you will get this output:
[mazda, toyota]
If you want each one on a separate line, you will need to iterate through the list in main
and print each one:
for (Car c : race.find(1.0))
System.out.println(c.getName());
Upvotes: 3
Reputation: 6207
Two problems: 1, you can only return one Object
from a method, and 2, your method returns immediately when it finds a Car
in the requested position. You need to take a look at your return type and make some adjustments if you want to be able to print more than one car.
Instead, do something like this:
public List<Car> find(double position){
List<Car> cars = new ArrayList<Car>();
for(Car d:cars){
if(d.getPosition()==position){
cars.add(d);
}
}
return cars;
}
You would then need to do some iterating back in your main()
method to print out each returned car, like so:
for(Car car : race.find(1.0))
{
System.out.println(car.getName());
}
Upvotes: 0
Reputation: 26502
A couple of things here:
Car
, which means you will return literally one Car
object. If you want to return multiple, you will need to either return an array of cars (Car[]
) or a collection of cars (e.g. List<Car>
, Set<Car>
, etc.).double
values may not always be exactly what you'd expect (e.g. 1.0
might not always mean 1.0
, it could be 0.999999...
, etc). Either use integers, or see this answer (or similar) on how to compare double
values in Java. Upvotes: 2
Reputation: 20129
You need to change your return type from Car
to Set<Car>
. The reason is that when you find the first car (in this case the mazda) you execute the line return d;
. That means its the end of your function. What you need to do is declare a Set<Car>
locally in the function, and intead of writing return d
you write Set.add(d);
Upvotes: 0