LinuxQuestions.org
LinuxAnswers - the LQ Linux tutorial section.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
LinkBack Search this Thread
Old 10-10-2005, 11:39 AM   #1
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Rep: Reputation: 50
java- static messing with random number generation


well, I'm back! I can't believe I've ignored java for this long. Anyway, I'm refreshing my brain with a little tool- a shuffling program.

I want to do this OO like, no cheating (last time I did this program I cheated by putting it all in public static void main- which isn't really reusable.)

The problem? the jazz about "you can't reference non-static variable x from a static context" here's my code:

Code:
import java.util.Random;

public class shuffly {
   
  static Random random = new Random();
  static int gens;
  
  protected static void shuffler(int lens) {
    //purpose: to take the amount of numbers given and shuffle them
    int[] nums = new int[lens];
    bigloop: for (int i = 0; i < nums.length; i++) {           // take the next empty array position
      gens = random.nextInt(lens-1);                       // generate a number in between 0 and lens
      for (int j = 0; j < nums.length; j++) {         //cycle through the array looking for duplicates
        if (nums[j] == gens) {
          continue bigloop;
        }
        if (nums[j] == 0) {
          continue bigloop;
        }
        
      }

    System.out.println("Shuffly Shuffler");
    System.out.print("[");
    for (int k = 0; k < nums.length; k++){
    System.out.print(nums[k] + " ");
    }
    System.out.print("]");
    System.out.println(" ");
    }

  }
  public static void main(String args[]) {
    shuffler(9);    
  }
}
more details? this is the way it will compile and run- but the output is all zeros when it should be an array of shuffled numbers. I'm guessing that you can't static the random generation of numbers. The fix for the first error is to make shuffler static, you can't remove static from the main- otherwise it won't run.

thanks- any clarification needed, just ask!

titanium_geek
 
Old 10-10-2005, 01:50 PM   #2
taylor_venable
Member
 
Registered: Jun 2005
Location: Indiana, USA
Distribution: OpenBSD, Ubuntu
Posts: 892

Rep: Reputation: 39
The reason you get all zeros is because you don't assign any values into the nums array. They just stay at their Java-initialized values of zero.

The "non-static method shuffler(int) cannot be referenced from a static context" error is because if a method is not listed as being static, it's an instance method. You can't reference an method that's supposed to be member to an instantiated class without indicating which instance it's part of. That's why you have to put the "static" modifier in front of the method definition to make it compile.

If you really want to make it object-oriented, you need a Shuffly class, and another class with main(...) in it. Then instantiate a Shuffly object within main(...) and call the method, like this:
Code:
public static void main(String[] args) {
    Shuffly shuffleObject = new Shuffly();
    shuffleObject.shuffler(9);
}
Of course, this means you also have to write a constructor for Shuffly. I would recommend that, and then using your Shuffly static variables as private instance variables, unless they need to be shared amongst various Shuffly instantiations.
 
Old 10-10-2005, 02:44 PM   #3
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
yay! great- this OOP stuff is tough after the ingrained habits of basic... grr. anyway- thanks, I've got some ideas to play with.

thankyou so much.

titanium_geek
 
Old 10-10-2005, 05:14 PM   #4
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
ok- I have been searching- how do I write a constructor?

obviously it is a "method" the same name as the class, but after that I'm stuck.

titanium_geek

Last edited by titanium_geek; 10-10-2005 at 05:16 PM.
 
Old 10-10-2005, 05:48 PM   #5
taylor_venable
Member
 
Registered: Jun 2005
Location: Indiana, USA
Distribution: OpenBSD, Ubuntu
Posts: 892

Rep: Reputation: 39
Java Constructors

Java constructors are just places to do initialization stuff. The VM automatically takes care of all memory allocation, &c. The most basic class / constructor combination would be:
Code:
public class Foo {
    // var declarations go here
    public Foo() {
        // initialize vars, if you need to
    }
}
In other code, you utilize this with:
Code:
Foo bar = new Foo();
Of course, constructors can take parameters and be overloaded, like any other method. There's more, too, like inheritance and such, but you can find that stuff elsewhere.

Note the "public" modifier in the class declaration above. If that class will only be accessed by other classes in the same file, you can omit the "public". But if you intend on reusing this class, better keep the "public" on there.
 
Old 10-10-2005, 08:07 PM   #6
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
cool- so I can just jam the basics in there and that's that. awesome.

thanks a TONNE.

titanium_geek
 
Old 10-13-2005, 01:24 PM   #7
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
ok- next dumb question- how do I pass out the data? I don't want to be restricted to System.out.println for output- I wanna be able to grab the data and play with it (ie, using the shuffler to shuffle 4 arrays in another program.)

thanks.

titanium_geek
 
Old 10-14-2005, 11:09 AM   #8
taylor_venable
Member
 
Registered: Jun 2005
Location: Indiana, USA
Distribution: OpenBSD, Ubuntu
Posts: 892

Rep: Reputation: 39
If your arrays are stored as instance variables within the class, you can just write a simple little accessor method to return them, so for instance:
Code:
 public class Foo {
    private int[] bar;
    ...
    int[] getBar() {
        return this.bar; // to return a reference to bar
        return (int[])this.bar.clone(); // to return a new copy of bar
    }
}
The first line gives the callee a reference to the array; it allows the array to be modified outside of class Foo, even though it's private. The second line returns an array that contains identical values to what's currently in bar. But if the returned value is modified, it won't affect the private bar inside Foo, because they're totally separate objects. The cast to an int array is necessary on the second line because clone() returns an Object.

Which method you want to use is up to you, it depends on how your class functions. In most circumstances, I'd probably recommend the second; as a rule of thumb, it's usually best to isolate, and control access to, instance-specific data as much as possible.
 
Old 10-15-2005, 01:39 PM   #9
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
Thankyou SO much! I understand!!!

titanium_geek
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Generate random number with C++ TruongAn Programming 5 11-09-2005 12:01 AM
random number generation sailu_mvn Programming 4 03-10-2005 02:10 PM
Random Number Game tearinox Programming 4 08-20-2004 10:12 PM
Generation of random primes SaTaN Programming 12 10-30-2003 04:30 PM
I need random number in C ... purpleburple Programming 4 10-28-2002 04:37 AM


All times are GMT -5. The time now is 04:44 AM.

Main Menu
 
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration