Results 1 to 3 of 3
  1. #1
    bpx95 is offline Member
    Join Date
    Apr 2011
    Posts
    8
    Rep Power
    0

    Default Probably Really Noob Question

    Okay, so I'm not really THAT noobish at Java, but right now I really feel like it. This has to be some really stupid misconception or something.

    Okay, so first of all:
    Java Code:
    	Random random = new Random();
    		for(int i=0; i<10; i++){
    			System.out.print(random.nextInt(2)*2);
    		}
    Returns either 0 or 2, always. Because 0*2 = 0 and 1*2 = 2.

    But then when I use it in a for-loop:

    Java Code:
    Random random = new Random();
    		for(int i=0; i<10; i++){
    			for(int j=0; j<random.nextInt(2)*2; j++)
    				System.out.print("1");
    			System.out.println();
    		}
    It acts as though it returns either 0, 1, or 2. I feel like it has to do maybe with the lack of the "1" possibility in the for-loop. Quite confused indeed. Why is it doing this?

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Java Code:
    random.nextInt(2)*2
    Using that in the condition of a loop is a really bad idea. Everytime it goes around the loop it will generate a different number so you can never guarantee how many times the loop will iterate.
    Java Code:
    Random random = new Random();
    for(int i=0; i<10; i++){
        int end = random.nextInt(2)*2;
        for(int j=0; j<end; j++) {
            System.out.print("1");
        }
        System.out.println();
    }
    If you change the code to that you should see more consistent results.

  3. #3
    bpx95 is offline Member
    Join Date
    Apr 2011
    Posts
    8
    Rep Power
    0

    Default

    Oh okay. I think I understand what you are saying. So I should generate the number and THEN run the loop, without using random.nextInt(2)*2 in the condition. That makes a lot of sense actually. I'll see if that works.

    EDIT: Ah ha! Thanks!

Similar Threads

  1. Noob question about using ints in booleans
    By elfdreaming in forum New To Java
    Replies: 6
    Last Post: 03-14-2011, 12:07 PM
  2. Reallyy noob question
    By x2robbie2x in forum New To Java
    Replies: 3
    Last Post: 02-18-2010, 05:58 AM
  3. Noob button question.
    By dudejonne in forum Java Applets
    Replies: 4
    Last Post: 10-20-2009, 11:51 PM
  4. Question - I'm a noob!
    By Insaeno in forum New To Java
    Replies: 5
    Last Post: 08-04-2008, 04:20 AM
  5. Noob question- easy
    By mattonitto in forum New To Java
    Replies: 7
    Last Post: 06-13-2008, 01:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •