Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hailstone Sequence without recursion (please)

Tags:

java

Hi there I am very new to coding and am taking an introductory Java class with a teacher that expects you to already know everything. I have to code the Hailstone Sequence, which is expressed as:

Pick some positive integer and call it n. If n is even, divide it by two. If n is odd, multiply it by three and add one. Continue this process until n is equal to one.

We have not learned recursion or arrays and he says we do not need to use it in this code, though I'm not all too sure what that means. We are to show the steps taken to get to one using the sequence formulas.

This is what I have and I have the following problems:

  • It won't recognize odd/even integers
  • It is showing the wrong number in the steps taken

Please help me recognize where I am going wrong and provide explanation. I am desperate.

import javax.swing.JOptionPane;
public class Hailstone {

public static void main(String[] args) {
    String output = "";
    int n;     
    n = Integer.parseInt(JOptionPane.showInputDialog("\nEnter an Integer"));

    while (n != 1) {
        int result = 0;
        if (n%2 == 0) {
            result = n /= 2; 
            output += n + " is even so I took half  =   " + result;     
            JOptionPane.showMessageDialog(null, output); 

        }else{
            result = n*3 + 1;
            output += n + " is odd so I took 3n+1 = " + result;     
            JOptionPane.showMessageDialog(null, output); 

    }

    }

}  
} 
like image 699
Natalia Avatar asked Jan 25 '26 03:01

Natalia


1 Answers

This statement: result = n /= 2; does not do what you think it does. It divides n by 2, stores the result in n, and then also stores the result in result. However, that's not the main problem with your code.

The problem is that you are missing one very simple little thing: to update n in the loop. Without this, n will never change. (Except for the accidental modification that I mentioned above.)

So, all you need to do, (after fixing the above problem,) is the following:

Right before the end of your loop, add this line:

n = result;

like image 172
Mike Nakis Avatar answered Jan 26 '26 16:01

Mike Nakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!