2 Replies - 472 Views - Last Post: 21 November 2014 - 02:00 PM Rate Topic: -----

#1 Alexmackzie   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 23-October 14

Random array is giving weird outputs

Posted 21 November 2014 - 05:41 AM

Hello! i am wrirting a program that creates an array with random numbers. Then the user can choose what number of the array he/she wants to check the occurance of. This works fine, but the numbers generated seems very weird, only 2 of the 10 possible numbers are generated. 0 and one of the other 9 numbers, the 0 is always 10100 and the other one is always 101.

import java.util.Random;
import java.util.Scanner;

public class OppgaveC {
	public static void sjekk() {
		
        int randomArray[]=new int[101];
        int countArray[]=new int[10];
        Random rand = new Random();
        
        for( int i=1 ; i<randomArray.length ; i++ )
		{
		randomArray[i] = rand.nextInt(10);
		
		//to store the counts
   
        for( int j = 0; j < randomArray.length; j++)
		for (int x : randomArray)
		    countArray[x]++;

		//to access the counts
		for (int x = 0; x < countArray.length; x++) {
		Scanner scan = new Scanner(System.in);
		System.out.println("What number do you want to check?");
		int num = scan.nextInt();
		if(num<= countArray.length)
		    System.out.println("" + num + " occurs " + countArray[num] + " times");
		else{
			System.out.println("That number is invalid, please choose a number between 0-" + countArray.length);
		}
			}
		}
	}
}



it also says i have a memory leak on my scanner, ow can i close this? Ty in advance! -Alex

Is This A Good Question/Topic? 0
  • +

Replies To: Random array is giving weird outputs

#2 aks29921   User is offline

  • D.I.C Regular

Reputation: 116
  • View blog
  • Posts: 345
  • Joined: 24-August 09

Re: Random array is giving weird outputs

Posted 21 November 2014 - 09:00 AM

Close your for loops at correct places. Try to think which one should be closed after what line. Right now all your loop brackets are closed at the end meaning that stuff that should be called only once would also be invoked multiple times.
Was This Post Helpful? 1
  • +
  • -

#3 Alexmackzie   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 23-October 14

Re: Random array is giving weird outputs

Posted 21 November 2014 - 02:00 PM

Ahh, thats embarrasing. Such an easy fix. Thank you very much:)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1