Code is missing a return - Help!
public boolean isBooked(int day,int time){
StringTokenizer tk = new StringTokenizer(bookings);
while (tk.hasMoreTokens()){
String str = tk.nextToken();
if (str.startsWith(day+"^"+time)){
return true;}
else{
return false;}
}
}
1 error found:
File: F:\UTM\csc108h\Test\Car.java [line: 63]
Error: missing return statement
[400 byte] By [
salonaha] at [2007-10-2 4:45:56]

> while (tk.hasMoreTokens()){
If tk.hasMoreTokens() is false at the start, then you'll never get to the if statement, which contains the only returns.
Even if you can guarantee somehow that it will always return true the first time, the compiler can't, so you'll need to add a return after the loop.
However, I question your code. Why use a loop if during the first iteration you're always going to return a value? You might as well not use the loop.
Just say:
public boolean isBooked(int day,int time){
StringTokenizer tk = new StringTokenizer(bookings);
if (tk.hasMoreTokens()) { // changed while loop to if statement
String str = tk.nextToken();
if (str.startsWith(day+"^"+time)){
return true;
} else {
return false;}
}
else {
return false;
}
}
> public boolean isBooked(int day,int time){
> StringTokenizer tk = new
> new StringTokenizer(bookings);
>while (tk.hasMoreTokens()){
What if this returns false the first time?
>String str = tk.nextToken();
>if (str.startsWith(day+"^"+time)){
> return true;}
>else{
> return false;}
>}
>}
>
>
> 1 error found:
> File: F:\UTM\csc108h\Test\Car.java [line: 63]
> Error: missing return statement
> Try taking the return statement out of the if/else
> block and do something like this instead.
> boolean boo;
> if (str.startsWith(day+"^"+time)){
> boo = true;}
> else{
> boo = false;}
> return boo;
>
This is not necessary. The problem is the condition in the while loop.