Reputation: 1
The code below should loop to produce:
It should print 1: Lather and Rinse
2: Lather and Rinse
Done.
It produces:
1: Lather and Rinse
Done.
import java.util.Scanner;
public class ShampooMethod {
public static void printShampooInstructions(int numCycles) {
if (numCycles < 1) {
System.out.println("Too few.");
return;
}
else if (numCycles > 4) {
System.out.println ("Too many.");
return;
}
else {
for (int i = 1; i <= numCycles; i++) {
System.out.print(+ i);
System.out.println(": Lather and rinse.");
System.out.println("Done.");
return;
}
}
}
public static void main (String [] args) {
printShampooInstructions(2);
return;
}
}
Upvotes: 0
Views: 183
Reputation: 367
The return statement will immediately cause the method to return, therefore the loop will stop on first pass. Remove the return statement from your loop and it shall work.
Upvotes: 0
Reputation: 37404
You have to remove the return;
statement otherwise your loop will stop in first pass
for (int i = 1; i <= numCycles; i++) {
System.out.print(i); // no need of +
System.out.println(": Lather and rinse.");
//return; //remove this
}
System.out.println("Done.");
Upvotes: 2
Reputation: 44831
You return
inside the loop, so the method exits the first time through. Remove the return
.
Also, it's not really a good practice to declare variables inline. Put your declaration at the start of the method and just initialize it in the for
statement.
Upvotes: 1