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 19 of 19

Thread: Put a random number from one vector to another

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Put a random number from one vector to another

    I have a problem with this code. The program is supposed to read a vector with Standard Input and choose randomly from that vector, put those numbers in another array and then print that array out. How large the first array is depends on N, from args, the size of the sample vector is M. Vector M is not supposed to choose the same number twice.
    It seems that the calling method does'nt work from main readInt and to static readInt method and I don't know how to fix it.

    public class Permexamp{
     
    	//Reading the vector with StdIn
    	public static int [] readInt(int N)
    	{
    		int [] vectora = new int [N];
    		for (int i = 0;i<N;i++){
    		vectora [i] = StdIn.readInt();
    	}		
    	return vectora;
     
            }
     
    		//Building a now vector chosen randomly from vectora, not choosing the same number 2
    		public static int[] randomchoose(int [] a, int M) {
    		int [] vectorb = new int [M];
    			for (int i = 0; i < M; i++)  
    			{	
    				int r = i + (int) (Math.random() * (M-i)); 
    				int t = vectorb[r];
    				vectorb[r] = vectorb[i];
    				vectorb[i] = t;
    			}
    			return vectorb;
    		}
    		//Main call's the other methods and prints out vectorb
    		public static void main(String args[])
    		{
    			int N = Integer.parseInt(args[0]);
    			int M = Integer.parseInt(args[1]);
    			int[] vectora = readInt(N);
    			int[] vectorb = randomchoose(vectora,M);
     
    			 for (int i = 0; i < M	; i++)
    				StdOut.println(vectorb[i]);
    		}
    	}

    When I compile it there are no errors. But the program seems to be in infenite loop. I do ctr Z to stop the program I get this error:

    ^Z
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at StdIn.readInt(StdIn.java:139)
    at Permexamp.readInt(Permexamp.java:8)
    at Permexamp.main(Permexamp.java:29)


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    Give us example values for M and N.

    Are you sure the program isn't just waiting for data entry from the keyboard? Have you tried entering values after running? It might be helpful to add a prompt to the readInt() method.

    Also, it's not a great practice to name your own methods the same as existing methods in the libraries you're using, even if the signatures are not the same. It's confusing, and the confusion is unnecessary.

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

    JohnJohnson123 (October 4th, 2013)

  4. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    Example values: Well the Vectora is supposed to be larger, because that is the array wich M is suppose to read from. So N>M, hopefully. I tried with 5 and 2 from the command line, nothing happened, I had the same error as before. Perhaps I should try other values...I think it has something to do with exactly that line you mentioned.

    --- Update ---

    update:
    line 14:public static int[] randomchoose(int [] vectora, int M) {

    --- Update ---

    This is where I'm at now. My problem is in line 8 and I dont know how to fix it...


     
    public class Permexamp{
     
            //Reading the vector with StdIn
            public static int [] readfromargs(int N)
            {
                int [] vectora = new int [N];
                    for (int i = 0;i<N;i++){
                        vectora [i] = Integer.parseInt(args[i]);//StdIn.readInt();
                        }        
                        return vectora;
            }
     
            //Building a now vector chosen randomly from vectora, not choosing the same number 2
            public static int[] randomchoose(int [] vectora, int M) {
            int [] vectorb = new int [M];
                for (int i = 0; i < M; i++)  
                {    
                    int r = i + (int) (Math.random() * (M-i)); 
                    int t = vectorb[r];
                    vectorb[r] = vectorb[i];
                    vectorb[i] = t;
                }
                return vectorb;
            }
            //Main call's the other methods and prints out vectorb
            public static void main(String args[])
            {
                int N = Integer.parseInt(args[0]);
                int M = Integer.parseInt(args[1]);
                int[] vectora = readfromargs(N);
                int[] vectorb = randomchoose(vectora,M);
     
                 for (int i = 0; i < M    ; i++)
                    System.out.println(vectorb[i]);
                    //StdOut.println(vectorb[i]);
            }
        }

    error message:

    Permexamp.java:8: error: cannot find symbol
    vectora [i] = Integer.parseInt(args [i]);//StdIn.readInt();
    ^
    symbol: variable args
    location: class Permexamp

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    The array args[] is local to the main() method, not within the scope of other methods even in the same class. Any values in args[] (or args itself) that are needed should be stored in other variables and passed to methods as needed.

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

    JohnJohnson123 (October 4th, 2013)

  7. #5
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I don't get it. How do I make it public? (Do you put it like that?)

  8. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    As I said pretty clearly, the necessary values or the whole array itself could be passed to the method:

    Change the call in main() to:
    int[] vectora = readfromargs( N, args );

    And change the method signature to:
    public static int [] readfromargs(int N, String[] args )

    BTW, to comply with Java's naming conventions, your method names should be: readFromArgs() and randomChoose().

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

    JohnJohnson123 (October 4th, 2013)

  10. #7
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    Thanks man.

    That goes a long way.

    I still get this error message. I'll look in tomorrow.

    >java Permexamp 5 2
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at Permexamp.readFromArgs(Permexamp.java:10)
    at Permexamp.main(Permexamp.java:32)

  11. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    Okay, but I'm not sure it's the right way. If args[] only contains two values M and N, and they've already been extracted and parsed to the desired values, I'm not sure why you'd pass the args[] array around. Pass M and N around and leave args[] out of it. Further, if args[] contains fewer elements than vectors[], they can't be compared element-by-element as is being done in readFromArgs();

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

    JohnJohnson123 (October 5th, 2013)

  13. #9
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I think the problem is that I'm not thinking this correctly. If I put for example 5 and 2 in command line the vectora.length(N) is 5. Then the program starts to parse(move) 5 and 2 into vectora but as string.args length (not sure if that is the correct saying...) is only two (M) the array is ''out of bounds''.

    Now...if N=4 and M=2, vectora is like{1,2,3,3} how do I create M from the command line?

  14. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    You've analyzed the source of the error correctly: can't cram 10 pounds into a 5 pound sack. I also think the two arrays hold different types of data, and that's a problem. And I agree with your realization that the design needs to be modified. What changes are you considering?

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

    JohnJohnson123 (October 5th, 2013)

  16. #11
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I'm thinking...two things perhaps I can ''ask'' first for N and then do system out print to ask for M. Or keep the code that I've got[ain't that just the code of my dreams...hahah] and create N numbers with math.random....

    update:

    The N is supposed to come from command line, just some normal vector like {1,2,3,3}....

  17. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    I suggest falling back and regrouping with a minor rethink, starting with the requirements. Sometimes we get set on a programming course not recognizing that we've either set out in the wrong direction to begin with or we've taken a wrong turn along the way, forgetting entirely where we're headed but pushing ahead undaunted.

    The requirements (my interpretation of your interpretation, please check them):

    1. read a vector with Standard Input of size N which is obtained from args[]
    2. choose randomly from that vector
    3. put those numbers (from the chosen vector) in another array of size M from args[], M <= N
    4. print that (the other) array out.
    5. the second vector M is not supposed to choose the same number twice (not contain duplicate numbers.)

    General comment: The assignment specifically states that a Vector is to be used which is a specific collection in Java, yet you're using arrays as vectors. Why is that? args[] is not and cannot be a Vector.

    Step 1: Obtain N and M from args[] and ask the user to provide N values to fill the first Vector. The readFromArgs() method is misguided.
    Steps 2, 3, and 5: choose M values randomly from the first vector and store those in a second vector, ensuring no duplicates are chosen.
    Step 4: Print the resulting second array.

    Now apply the rethink to some code changes.

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

    JohnJohnson123 (October 5th, 2013)

  19. #13
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I tried some changes at the bottom, I tried changing the sequence of the creation of the arrays. With the input {2,2,2,2} the program prints out:0
    0

    public class Permexamp{
     
            //Reading the vector with StdIn
            public static int [] readFromArgs(int N, String[] args)
            {
                //int N = args.lenght;
                int [] vectora = new int [N];
                    for (int i = 0;i<vectora.length;i++){
     
                        vectora [i] = Integer.parseInt(args [i]);//StdIn.readInt();
                        }        
                        return vectora;
            }
     
            //Building a now vector chosen randomly from vectora, not choosing the same number 2
            public static int[] randomChoose(int [] vectora, int M) {
            int [] vectorb = new int [M];
                for (int i = 0; i < M; i++)  
                {    
                    int r = i + (int) (Math.random() * (M-i)); 
                    int t = vectorb[r];
                    vectorb[r] = vectorb[i];
                    vectorb[i] = t;
                }
                return vectorb;
            }
            //Main call's the other methods and prints out vectorb
            public static void main(String args[])
            {
                int N = Integer.parseInt(args[0]);
                //int M = Integer.parseInt(args[1]);
                int[] vectora = readFromArgs( N,args);
                int M = Integer.parseInt(args[1]);
                int[] vectorb = randomChoose(vectora,M);
     
                 for (int i = 0; i < M    ; i++)
                    System.out.println(vectorb[i]);
                    //StdOut.println(vectorb[i]);
            }
        }

    I was just seeing your last post. Yeas I'll sit down and think this over a bit.

    --- Update ---

    You're absolutely correct.

    --- Update ---

    So it should perhaps be something like this? I'm...having trouble with step 1. I need N and M [to bad it's not M&M] and N-values/vector?

    public static void main(String args[])
            {
                int M = Integer.parseInt(args[0]);//Choose from these numbers
                int N = Integer.parseInt(args[1]);//This many numbers
                int[] vectora = readFromArgs( N,args );
                int[] vectorb = randomChoose(vectora,M);
     
                 for (int i = 0; i < M    ; i++)
                    System.out.println(vectorb[i]);
                    //StdOut.println(vectorb[i]);
            }
        }


    --- Update ---

    Could it be like N= vectora and the length of that vector=how many numbers to choose from?
    Last edited by JohnJohnson123; October 5th, 2013 at 07:31 AM. Reason: update:

  20. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    Something more like this:
    public static void main(String args[])
            {
                // i think you have M and N backwards, but I may not understand your comments
                int M = Integer.parseInt(args[0]);//Choose from these numbers
                int N = Integer.parseInt(args[1]);//This many numbers
     
                // fills vectora with N values supplied by the user
                int[] vectora = getUserInput( N );
     
                int[] vectorb = randomChoose( vectora, M );
     
                // output the resulting vector
            }
        }
    I'm getting the impression you think the values of vectora come from args[], but I think the user enters those values later.

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

    JohnJohnson123 (October 5th, 2013)

  22. #15
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I'm lost...

    public class Permexamp1{
     
            //Reading the vector with StdIn
            public static int [] getUserInput(int N)
            {
                //int N = args.lenght;
                int [] vectora = new int [N];
                    for (int i = 0;i<vectora.length;i++){
     
                        vectora [i] =Integer.parseInt(args[i]);// StdIn.readInt();
                        }        
                        return vectora;
            }
     
            //Building a now vector chosen randomly from vectora, not choosing the same number 2
            public static int[] randomChoose(int [] vectora, int N) {
            int [] vectorb = new int [M];
                for (int i = 0; i < N; i++)  
                {    
                    int r = i + (int) (Math.random() * (N-i)); 
                    int t = vectorb[r];
                    vectorb[r] = vectorb[i];
                    vectorb[i] = t;
                }
                return vectorb;
            }
            //Main call's the other methods and prints out vectorb
            public static void main(String args[])
            {
                int M = Integer.parseInt(args[0]);
                int N = Integer.parseInt(args[1]);
                int[] vectora = getUserInput(N );
                int[] vectorb = randomChoose(vectora,M);
     
                 for (int i = 0; i < M    ; i++)
                    System.out.println(vectorb[i]);
                    //StdOut.println(vectorb[i]);
            }
        }

    Compile it in Jeliot. Input: 5 5

    Error:Execution Error
    Line 12, Column 51:
    Undefined class or field 'args'.
    Last edited by JohnJohnson123; October 5th, 2013 at 09:11 AM. Reason: update

  23. #16
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,402
    My Mood
    Mellow
    Thanks
    83
    Thanked 472 Times in 463 Posts

    Default Re: Put a random number from one vector to another

    You are where you were several posts ago. Same code, same errors, different method names. Short of writing this for you, I'm not sure how to reboot you so that you start rethinking what you're doing, because this isn't hacking it. args[] has nothing to do with getting user input.

    getUserInput() should look something like this:
    //Reading the vector with StdIn
    public static int[] getUserInput( int N )
    {
        Scanner input = new Scanner( System.in );
     
        //int N = args.lenght;
        int[] vectora = new int[N];
     
        for (int i = 0 ; i < vectora.length ; i++ )
        {
            System.out.print( "Enter element " + ( i + 1 ) + ": " );
            vectora[i] = input.nextInt();// StdIn.readInt();
     
            // read the linefeed and throw it away (flush the buffer)
            input.nextLine();
     
            // add a linefeed between prompts
            System.out.println();
        }
     
        input.close();
     
        return vectora;
    }
    That's all I'll do, and it may not be exactly right. Hope it helps.

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

    JohnJohnson123 (October 5th, 2013)

  25. #17
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Put a random number from one vector to another

    args is an array limited in scope to the main method. You're trying to use it inside your getUserInput(), but as far as that method is concerned, the args array does not exist.

            //Reading the vector with StdIn
            public static int [] getUserInput(int N)
            {
                //int N = args.lenght;
                int [] vectora = new int [N];
                    for (int i = 0;i<vectora.length;i++){
     
                        vectora [i] =Integer.parseInt(args[i]); //WHAT IS ARGS[I]??????
                        }        
                        return vectora;
            }
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  26. The Following User Says Thank You to newbie For This Useful Post:

    JohnJohnson123 (October 5th, 2013)

  27. #18
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    I'm wondering. Is this something to build on...

    I'll have to ''build'' the methods again...but than again the other stuff I got is trash...

    public class Sample1{
     
    //public class Sample1 {
        public static void main(String[] args) {
            int M = Integer.parseInt(args[0]);    // choose this many elements
            int N = Integer.parseInt(args[1]);    // from 0, 1, ..., N-1
     
            // create permutation 0, 1, ..., N-1
            int[] perm = {8,1,2,3,5,6,7,8};  //new int[N];
            for (int i = 0; i < N; i++)
                perm[i] = i;
     
            // create random sample in perm[0], perm[1], ..., perm[M-1]
            for (int i = 0; i < M; i++)  {
     
                // random integer between i and N-1
                int r = i + (int) (Math.random() * (N-i));
     
                // swap elements at indices i and r
                int t = perm[r];
                perm[r] = perm[i];
                perm[i] = t;
            }
     
            // print results
            for (int i = 0; i < M; i++)
            System.out.print(perm[i] + " ");
            System.out.println();
        }
    }

  28. #19
    Junior Member
    Join Date
    Sep 2013
    Posts
    22
    Thanks
    17
    Thanked 0 Times in 0 Posts

    Default Re: Put a random number from one vector to another

    It seems that #13 was correct. Thanks for your help and patiance.

Similar Threads

  1. Random number
    By Imran Ahmad in forum Java Theory & Questions
    Replies: 1
    Last Post: April 30th, 2012, 11:53 AM
  2. Generation of random number using random class
    By JavaPF in forum Java SE API Tutorials
    Replies: 1
    Last Post: December 7th, 2011, 04:46 PM
  3. How to returned random number to original number?
    By i4ba1 in forum Algorithms & Recursion
    Replies: 2
    Last Post: March 19th, 2011, 04:35 AM
  4. HELP. Random Number Between
    By Raymond Pittman in forum Java Theory & Questions
    Replies: 3
    Last Post: February 15th, 2011, 08:50 AM
  5. Generation of random number using random class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: April 16th, 2009, 06:10 AM