# Need some help for a school project.

• 10-19-2013, 04:46 AM
Jaxful
Need some help for a school project.
So, im working on this schoolwork that i was supposed to finish in class today, and im close. We are supposed to use the Collatz sequence to get any random integer above 0 to be 1, and say how many iterations it took, and the highest number there was , but i cannnot figure out how to print the highest number, any help would be appreciated.

here is my code.

import java.util.Scanner;
public class Collatz
{
public static void main(String args[] )
{
int num;
int i = 0;
int max = 0;
Scanner s = new Scanner (System.in);
do
{
System.out.println("Please enter a starting number above 0: ");
num = s.nextInt();
}
while (0 > num);

while (num != 1)
{
if (num%2 == 0)
{
num = (num / 2);
System.out.println(num);
i = i + 1;
}

else if (num%2 == 1)
{
num = (num * 3) + 1;
System.out.println(num);
i = i + 1;
}

}
System.out.println("Terminated after " + i + " iterations ");
if (max < num)
{
max = num;
System.out.println("The highest number is " + max);
}

}
}
• 10-19-2013, 04:52 AM
donohoes
Re: Need some help for a school project.
could you not and another int highNum and then check if (num>highNum){ highNum==num}
• 10-19-2013, 04:56 AM
Jaxful
Re: Need some help for a school project.
Did that at the bottom of the code but im not sure if i did it right...
if (max < num)
{
max = num;
System.out.println("The highest number is " + max);
}
• 10-19-2013, 05:28 AM
donohoes
Re: Need some help for a school project.
its should be more inside the while loop so that it actully chages with num
• 10-19-2013, 11:42 PM
superhaNds
Re: Need some help for a school project.
What donohoes said and also in your do-while loop, the condition 0 > num would cause trouble if 0 is entered, change it to 0 >= num