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)