# Learn Java Coding

Everything You Have To Know About Java

The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz. The problem is stated as follows: start with any positive integer n.  If n is even, the next number is n/2, if n is odd, the next number is 3n+1. The conjecture is that no matter what value of n, the sequence will always have as end values 4, 2, 1, 4, 2, 1, … . In this program, we will simulate the process until it reaches the number 1.

To create this program in Java we have to:

1. Create a package PackageCollatz

2. Create a class ClassCollatz

3.  Implement the example model (the spinal cord) of every program.

4. import the PrintStream and Scanner Class

``````package PackageCollatz;

import java.io.PrintStream;
import java.util.Scanner;

public class ClassCollatz {
PrintStream out;
Scanner in;

ClassCollatz () {
out = new PrintStream(System.out);
in = new Scanner(System.in);
}

void start() {

}

public static void main(String[] argv) {
new ClassCollatz().start();
}
}``````

5. The next step is to check if the number that the user gives as input is even or odd.

This could we do with the following lines:

``````out.printf("Enter a positive integer: ");
int variable1 = in.nextInt();
int variable2 = variable1 % 2;

if (variable2 == 0) {
variable1 = (variable1 / 2);
} else {
variable1 = (3 * variable1 + 1);
}
out.printf("%d ", variable1);``````

6. The last step is to create a loop that will loop until variable1 is a one.

``````out.printf("Enter a positive integer: ");
int variable1 = in.nextInt();

out.printf("%d ", variable1);
while (variable1 != 1) {
int variable2 = variable1 % 2;

if (variable2 == 0) {
variable1 = (variable1 / 2);
} else {
variable1 = (3 * variable1 + 1);
}
out.printf("%d ", variable1);
}
``````

!= is not equal to

### The Program:

``````package PackageCollatz;

import java.io.PrintStream;
import java.util.Scanner;

public class ClassCollatz {
PrintStream out;
Scanner in;

ClassCollatz () {
out = new PrintStream(System.out);
in = new Scanner(System.in);
}

void start() {
out.printf("Enter a positive integer: ");
int variable1 = in.nextInt();

out.printf("%d ", variable1);
while (variable1 != 1) {
int variable2 = variable1 % 2;

if (variable2 == 0) {
variable1 = (variable1 / 2);
} else {
variable1 = (3 * variable1 + 1);
}
out.printf("%d ", variable1);
}

}

public static void main(String[] argv) {
new ClassCollatz().start();
}

}``````