Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Can't Break Out of a Loop

Dari Ko
Greenhorn
Posts: 1
// Allows for input from user.
import java.util.Scanner;
// Allows for use of the printf method.
import java.io.PrintStream;

/*
* Class that uses several different types of loops to find the factorial
* of a given number and print a table of dimensions for several rectangles.
*/
public class LoopExamples {

public boolean replay;

// Uses a while loop to find the factorial of a given integer.
public int factorial(int i){

int factorial = 1;
do{

while(i > 0){

factorial = factorial * i;
i--;

}
return factorial;

}while(replay = true);

}

/*
* Asks the user if he or she would like to calculate another factorial.
* The factorial method will either quit or re-run depending on the answer.
*/
public void again(boolean replay){

System.out.println("Would you like to calculate another factorial?");
Scanner s = new Scanner(System.in);
replay = true;
replay = false;
else

LoopExamples a = new LoopExamples();
a.ifTrue(replay);
}

/* If the user wants to calculate another factorial, the user is asked for an integer,
* then the factorial method is called and the factorial given. If the user does not want
* to proceed further, then the program quits and moves on.
*/
public void ifTrue(boolean replay){

while (replay = false) {
System.out.println("Thanks for using the Factorial Calculator!");
break;}

while(replay = true){

Scanner s = new Scanner(System.in);
System.out.println("Please enter the integer to find the factorial of:");
int i = s.nextInt();

LoopExamples l = new LoopExamples();
int factorial = l.factorial(i);

System.out.println("The factorial of " + i + " is " + factorial + ".");

LoopExamples a = new LoopExamples();
a.again(replay);

}
}

// Method main that calls the other methods.
public static void main(String[] args) {

System.out.println("Welcome to the Factorial Calculator!");

LoopExamples a = new LoopExamples();
boolean replay = true;
a.ifTrue(replay);

}
}

This is my code.
Even if I enter "n" or "N" when asked if I want to calculate another factorial, it doesn't break. Instead it goes back and asks me to enter a new integer. Help?

fred rosenberger
lowercase baba
Bartender
Posts: 12234
36
while (replay = false) {

never do the above, and your non-working code is why. First, you probably meant to use '=='. but a better way would simply be:

while (!replay ) {