#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    NYC
    Posts
    11
    Rep Power
    0

    Question passing a variable into an array


    I need to pass a variable into an array, then print out the value entered and how many times it was entered. It needs to be an INT between 0 and 50, and -1 is the "out" key.

    I have the FOR loop down, which I think is necessary to run this, but I can't figure out how to 'store' the values entered into the array and then print them out. This is where I'm getting confused with the array process.

    Here's what I've got so far:

    Code:
    import java.io.*;
    public class Occur {
    	
    	public static void main (String [] args) throws IOException{
    		String input;
    		BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    
    		int value;
    		
    		int num[] = new int[50];
    		
    			
    		System.out.println("Enter a value between 0 and 50 [-1 to end]: ");
    		input = stdin.readLine();
    		value = Integer.parseInt(input);
    
    		for (int i=0; i < num.length; i++) {
    		num[i] = 0;
    		num[value]++;
    		}
    		
    		for (int i = 0; i < num.length; i++){			
    		if (num[i] > 0)	
    		System.out.println("The value of " + value + " has " + num[value] + " occurences");
    		}
    
    		
    											}
    				}
    Any help is appreciated.
    Last edited by apw420; July 2nd, 2003 at 11:27 PM.
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    10
    Rep Power
    0
    try replacing yr for loops with this:

    Code:
    for (int i=0; i < num.length; i++) {
                 num[i] = value;
    }
    		
    for(int i = 0; i < num.length; i++){
                int count =0;			
                
                for(int j=0; j<num.length; j++){
                       if(num[i] ==num[j])
                            count++;
                }
                 System.out.println("The value of " + num[i] + " has " + count + " occurences");
    }
    hope this helps..

    i'm not sure about num.length(), maybe using 50 is safer..
    Last edited by liya; July 8th, 2003 at 04:04 AM.

IMN logo majestic logo threadwatch logo seochat tools logo