Reputation:
The idea is different lots in an auction. I know I need a return statement of type "Lot" however I am not sure what that would be. Here is my code.
public Lot getLot(int lotNumber)
{
int index = 0;
boolean found = false;
while(index < lots.size() && !found) {
Lot selectedLot = lots.get(index);
if(selectedLot.getNumber() == lotNumber) {
found = true;
}
else {
index++;
}
}
if(!found) {
found = false;
}
}
Upvotes: 3
Views: 99
Reputation: 455
public Lot getLot(int lotNumber) {
int index = 0;
boolean found = false;
Lot selectedLot = null; //set initial value to null
while(index < lots.size() && !found) {
selectedLot = lots.get(index);
if(selectedLot.getNumber() == lotNumber) {
found = true;
} else {
index++;
}
}
return selectedLot; //You need to return type Lot
}
when you say Lot getLot(int lotNumber)
you are basically saying that you are returning an object of type Lot, but you never return it in your code
Upvotes: 1
Reputation: 60104
You could use following code:
1) returns last Lot with some number
public Lot getLot(int lotNumber)
{
int index = 0;
Lot resultLot = null;
while(index < lots.size() ) {
Lot selectedLot = lots.get(index);
if(selectedLot.getNumber() == lotNumber) {
resultLot = selectedLot;
}
else {
index++;
}
}
return resultLot;
}
2) or (returns first Lot with some number)
public Lot getLot(int lotNumber)
{
int index = 0;
while(index < lots.size() ) {
Lot selectedLot = lots.get(index);
if(selectedLot.getNumber() == lotNumber) {
return selectedLot;
}
else {
index++;
}
}
return null;
}
3) or (smaller example)
public Lot getLot(int lotNumber)
{
for(Lot selectedLot: lots) {
if(selectedLot.getNumber() == lotNumber) {
return selectedLot;
}
}
return null;
}
Upvotes: 2
Reputation: 313
What you could do is something similar to this, what this will do is if a match is found it will return the selectedLot which was the match, and if no match was found it would return null:
public Lot getLot(int lotNumber) {
int index = 0;
while(index < lots.size()) {
Lot selectedLot = lots.get(index);
if (selectedLot.getNumber() == lotNumber) {
return selectedLot;
} else {
index++;
}
}
return null;
}
Upvotes: 6