I tried implementing the Collatz Sequence using a while
loop, but I can't stop the sequence at 1. The code continues. I tried using all my possibilities, but I can't come up with a solution.
import java.util.Scanner;
public class cs{
public static void main(String[] args)throws Exception{
System.out.println("Starting number: ");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.print(" " + a);
while(a>1)
{
if(a == 1) break; // this is not working though
if((a % 2 ) == 0) {
a = a / 2;
System.out.print(" " + a);
}
Thread.sleep(1000);
if((a % 2) != 0){
a = (a * 3) + 1;
System.out.print(" " + a);
}
Thread.sleep(1000);
}
}
}
The second
if
condition here should be anelse
of the first one:Like this:
I also removed the
if (a == 1)
line which was pointless, as due to thewhile (a > 1)
condition, thatif
would never betrue
.Lastly, I recommend to pay more attention to indenting your code correctly, and to add spaces around operators like I did, otherwise the code is too difficult to read, understand and debug.