Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: I think I did something wrong here. I need some feedback...

  1. #1
    Member mjr's Avatar
    Join Date
    Jan 2012
    Location
    127.0.0.1
    Posts
    36
    My Mood
    Fine
    Thanks
    8
    Thanked 2 Times in 1 Post

    Default I think I did something wrong here. I need some feedback...

    Ok, I was recently writing a small java app that would print out values according to the Collatz Conjecture.

    Collatz conjecture - Wikipedia, the free encyclopedia

    Anyway, I noticed that after a certain number of iterations (i.e. the number being checked) the app just kind of sits there.

    So what I did was write output to the console every 10,000 numbers.

    Well, up to 100,000 it works fine. If I try it with 1,000,000, then it gets up to about 113,000 and just kinda hangs.

    I'm trying to have it write out the "hailstone number" at the given position.

    Here's sample output:
    1 0
    2 1
    3 7
    4 2
    5 5
    6 8
    7 16
    8 3
    9 19
    10 6

    I also have the code below. I'm wondering if this is a variable problem, a structure problem, or if I stumbled across some kind of limit that Java has. I wrote this same app in C# and ran into the same issue.

    Anyhow, here's the code (yes, I know it could probably use a good refactoring):

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import java.io.Writer;
     
    public class HailstoneNumbers {
     
    	private static Writer writer = null;
     
    	public static void main(String[] args) throws IOException {
     
    		long result = 0;
     
    		System.out.println("Writing File.");
    		try {
    			writer = new BufferedWriter(new OutputStreamWriter(
    			          new FileOutputStream("C:\\hailstones.txt"), "utf-8"));
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		for (int x = 1; x < 1000001; x++)
            {
                if (x % 10000 == 0)
                {
                    System.out.println(x + " numbers written.");
                }
     
                try
                {
                    result = calculateHailstone(x);
                }
                catch (Exception ex)
                {
                	ex.printStackTrace();
                	System.out.println("An error has occurred.");
                }
     
                writeFile(x, result);
     
            }
     
    		System.out.println("File Written.");
     
            writer.flush();
            writer.close();
     
            System.in.read();
    	}
     
    	private static long calculateHailstone(int number)
        {
            long steps = 0;
     
            if (number == 1)
            {
                steps = 0;
            }
     
            try
            {
                while (number != 1)
                {
                    if (number % 2 == 0)
                    {
                        number = number / 2;
                    }
                    else
                    {
                        number = (number * 3) + 1;
                    }
     
                    steps++;
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                System.out.println("An Error has occurred.");
            }
     
            return steps;
        }
     
    	private static void writeFile(int position, long hailstoneNumber)
        {
    		try {
    			writer.write(position + "\t" + hailstoneNumber + "\r\n");
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
    }

    Please note this is NOT a homework assignment. This was something I wrote just out of sheer curiosity.

    So, does anyone have any thoughts on why this functions the way it does?? I'm striving to become a better software engineer, and I'm trying to determine here if this is something I did or didn't do (or possibly did incorrectly).

    Thanks for any knowledge you may be able to pass along!


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: I think I did something wrong here. I need some feedback...

    I added the code below to the calculateHailstone() method before the steps increment as shown. What's happening?
    if ( number < 0 )
    {
    	System.out.println( "Number went negative" );
    	System.exit( 0 );
    }
     
    steps++;

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    mjr (October 23rd, 2013)

  4. #3
    Member mjr's Avatar
    Join Date
    Jan 2012
    Location
    127.0.0.1
    Posts
    36
    My Mood
    Fine
    Thanks
    8
    Thanked 2 Times in 1 Post

    Default Re: I think I did something wrong here. I need some feedback...

    Interesting. So if I understand what's going on correctly, I'm getting an uncaught overflow error. I thought I was using a large enough data type. Guess not.

    Am I correct there?

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: I think I did something wrong here. I need some feedback...

    Well, you're thinking and trying to make sense of what you observed, and there's nothing wrong with that.

    The reason for what you observed has to do with the way numbers are stored in computers. You can read about Java primities, and you'll see they range from some minimum number to some maximum. Let's say in the case of type int, they range from -100 to 99. Of course they're much larger, but for this discussion that's the range. When you see limits like that, you should ask yourself, "What happens when I add 1 to the upper limit, 99?"

    Go find the real maximum size of an int in Java and see what happens when you add 1 to it. Then see if you can figure out why what happens happens.

  6. The Following User Says Thank You to GregBrannon For This Useful Post:

    mjr (October 21st, 2013)

  7. #5
    Member mjr's Avatar
    Join Date
    Jan 2012
    Location
    127.0.0.1
    Posts
    36
    My Mood
    Fine
    Thanks
    8
    Thanked 2 Times in 1 Post

    Default Re: I think I did something wrong here. I need some feedback...

    I get what you're saying about the primitive types. I do notice that in my code above I'm using an int type for the "number" variable, and a long for the step variable. So the step variable can go up to 9,223,372,036,854,779,999 (or thereabout), whereas the int can only go up to 2147483647. Meaning that the long data type is approximately 4,294,967,298 bigger (if the math is right) than the int.

    So I think I'm on the right track here. Sending thanks your way!

  8. #6
    Member mjr's Avatar
    Join Date
    Jan 2012
    Location
    127.0.0.1
    Posts
    36
    My Mood
    Fine
    Thanks
    8
    Thanked 2 Times in 1 Post

    Default Re: I think I did something wrong here. I need some feedback...

    Ok, after some refactoring, I think I have it figured out. I changed the for statement in the original code to a while statement.

    I also changed the x variable to a long type instead of just an int. That seemed to do the trick.

    Thanks again for the point in the right direction!

Similar Threads

  1. Feedback on java assignment
    By MadMulken in forum Java Theory & Questions
    Replies: 2
    Last Post: July 3rd, 2013, 03:20 PM
  2. UML Feedback?
    By behedwin in forum Object Oriented Programming
    Replies: 2
    Last Post: October 13th, 2012, 11:13 AM
  3. My New Website | Feedback Please!
    By OA-OD-JD1 in forum Totally Off Topic
    Replies: 3
    Last Post: July 16th, 2012, 01:30 AM
  4. Our New Website - Feedback wanted
    By alanappromoter in forum Totally Off Topic
    Replies: 1
    Last Post: May 29th, 2012, 09:53 AM
  5. Feedback Wanted for My Website
    By KevinWorkman in forum The Cafe
    Replies: 17
    Last Post: October 6th, 2011, 06:57 AM