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

Thread: Counting input array

  1. #1
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Counting input array

    Hey, so I have to take user input and then count how many times each number that the user input and print each one out. For some reason, I can't even get the for loop statement to print and it's pretty much the same as my other program except for the loop which is a little different. Please help. I'm so confused.
    //User inputs numbers between 1 and 100, program counts how many of each integer is and ends with a 0
     
    import java.util.Scanner;
     
    public class occurrence {
     
    	public static void main(String[] args) {
     
    	//scanner/values
    		Scanner input = new Scanner(System.in);
    		int number = 0;
    		int c = 0; //array count
     
    	//array
    		int[] allNum = new int[c];
     
    	//for loop, user input
    		for (c = 0; number != 0; c++) {
    			System.out.print("Please enter integers from 1 to 100, enter 0 when finished: ");
    				number = input.nextInt();
    			allNum[number]++;
    		}				
    	}		
    }


  2. #2
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: Counting input array

    because you have a condition number != 0
    but initially you declared number = 0;
    therefore, it will never execute the loop since the condition number != 0 is false.

  3. #3
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    Oh wow, I'm dumb.. Thanks! I should think a lot more... So, how would I initialize that variable since I have to use it in the for loop and also as a user input?

  4. #4
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: Counting input array

    the question is:
    how many times you want to execute the codes in your loop?
    or in what way will your loop be terminated?

  5. #5
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    The loop terminates when the last number inputted is a 0, so that's why I put the <number != 0> in the loop.

  6. #6
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    A for loop is of the form
    for (initialization; termination; increment) {
        statement(s)
    }

    The loop terminates when the termination expression evaluates to false. See The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics). The idea of using number != 0 in the termination expression has merit, but as dicdic pointed out, it is undone by the earlier int number = 0. The valid values for number are 1 to 100 (from user input) and 0 (for termination). Therefore you can initialise it to a value outside the valid range.

    You have a further problem with your code even after you've got your for loop working:

    		int c = 0; // array count
     
    		// array
    		int[] allNum = new int[c];

    This initialises your array to a size of 0, and so you will not be able to put anything in it. allNum[number]++; will result in an ArrayIndexOutOfBoundsException. See Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics). Give it some thought as to how you should initialise the array. Pay close attention to the way an array is indexed, and relate that to how you would apply it to allNum[number]++;

  7. #7
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    I've been reading and correct me if I'm wrong, but do I have to use an <arrayList>? Because from what I've been reading, you HAVE to initialize the array to some kind of limit. And for the <number> initialization, do you mean I could put like, 101 for example, and it'd be fine?

  8. #8
    Member
    Join Date
    Sep 2013
    Posts
    70
    Thanks
    1
    Thanked 13 Times in 13 Posts

    Default Re: Counting input array

    An arrayList is just a re-sizable array and you are not need to use it.

    When you initialize an array and give it a number
    int[] i = new int[2];
    Think of it as this "Here is a container with 2 int slots for you to use" So now you can store or retrieve data from those 2 slots (0, 1). Now if you attempt to retrieve data i[10] then you will have an IndexOutOfBounds exception. Essentially you are telling it to retrieve a value from slot 11 but it is a non existent slot as the container you provided for it only has 2 spaces.

    Now if you set it up a
    int[] i = new int[15];
    You now have a container with 15 available slots. Keep in mind anytime you initialize an array as above it will have all of it's values set to 0. If you have predetermined values you could initialize it as such.
    int[] i = {2, 3, 922, 38, -18, 28}; // This array will be initialized and only be able to hold 6 elements.
    In an array the elements inside can be modified. For example in this array that was initialized with 6 elements you can changed any of their values. The thing you cannot do is add more slots. For example if you wanted it to have 100 slots then you would have had to initialized your array to that size since the beginning.

    In a small application I doubt it would make much of a difference using an array vs arrayList. The difference between them in my opinion is that you want to use an array when you know the amount of elements and you only want to allocate that amount of memory. The nice thing about an arrayList is that you can initialize it to the size you want to at first. Once all the slots get filled up it will re-size itself. It does this by internally creating a larger array copying then copying the elements over from the old array. This can become very expensive when dealing with a large amount of elements.

  9. #9
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    Quote Originally Posted by Elyril View Post
    I've been reading and correct me if I'm wrong, but do I have to use an <arrayList>?
    To summarise Ubiquitous' reply, you can use an ArrayList if you want. But do you have to? To answer that, find out if you can pre-determine the number of elements to initialise the array to.

    Quote Originally Posted by Elyril View Post
    Because from what I've been reading, you HAVE to initialize the array to some kind of limit. And for the <number> initialization, do you mean I could put like, 101 for example, and it'd be fine?
    Try it! What's the worst thing that can happen? :-) Programming involves experimentation, so just go for it and see what happens.

  10. #10
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    I have no idea what the number of elements is because the user can input any amount of numbers they can want as long as they don't enter 0 which ends the input. And that <101> initialization of <number> doesn't work... I also tried <number = max - min>, which also didn't work.

  11. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Counting input array

    Your use of angle brackets, '<>', is unclear and confusing, because those have a specific meaning in Java, but that specific meaning is not related to what you've posted. To help us understand what you're doing, post actual code, even snippets, and then describe what 'doesn't work' means.

  12. #12
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    Quote Originally Posted by Elyril View Post
    I have no idea what the number of elements is because the user can input any amount of numbers they can want as long as they don't enter 0 which ends the input.
    You don't need to know the amount of numbers the user wants to enter because the array is not for storing the series of numbers entered by the user. The biggest clue here is what you already have in your original post:

    allNum[number]++;

    The thing is your original code, apart from the shortcomings pointed out to you previously, is actually close to the final solution.

    Quote Originally Posted by Elyril View Post
    And that <101> initialization of <number> doesn't work... I also tried <number = max - min>, which also didn't work.
    I, too, am not too sure what you mean by the above. Best post your re-worked code here.

    Btw, is this a school/college assignment? I'm asking because it wouldn't be right for me to reveal the solution to you here if it is an assignment... :-)

  13. #13
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    Is the array for storing the amount of each number then? And yes, it's a college assignment. I added and changed a couple things, but I can't test it because I'm not sure how to make it so that the number input can be in a range instead of just 1 number. I'm also probably over thinking this anyway...
    //User inputs numbers between 1 and 100, program counts how many of each integer is and ends with a 0
     
    import java.util.Scanner;
     
    public class occurrence {
     
    	public static void main(String[] args) {
     
    	//scanner/values
    		Scanner input = new Scanner(System.in);
    		int number = 101; //101 doesn't work. (max-min) doesn't work. 0 doesn't work.
    		int c = 1; //array count
     
    	//array
    		int[] allNum = new int[c];
     
    	//for loop, user input
    		do {
    			System.out.print("Please enter integers from 1 to 100, enter 0 when finished: ");
    				number = input.nextInt();
    			allNum[number]++;
    			c++;
     
    		}	
    		while (number != 0);
     
    		if (allNum[number] == 1) {
    			System.out.println(number + " occurs " + allNum[number] + " time.");
    		}
    		if (allNum[number] > 1) {
    			System.out.println(number + " occurs " + allNum[number] + " times.");
    		}
    	}		
    }

  14. #14
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    Quote Originally Posted by Elyril View Post
    Is the array for storing the amount of each number then?
    Exactly, hence
    allNum[number]++;

    Remember, allNum[number]++ can be thought of as allNum[number] = allNum[number] + 1, i.e., increment the value of allNum[number] by 1.

    Since the valid input numbers are between 1 and 100, inclusive, you can conveniently use the input number as the array's index. This means you'll be storing the count of numbers in the array positions between allNum[1] and allNum[100].

    Quote Originally Posted by Elyril View Post
    		int c = 1; //array count
     
    	//array
    		int[] allNum = new int[c];
    If you look back at the tutorial at Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics), you'll see that Java array's index starts with 0. The above code initialises the allNum array to a size of 1, and so you'll only be able to store a value at position allNum[0].

    If you, say, initialise the array like this:
    int[] allNum = new int[5];

    you'll be able to store values at positions
    • allNum[0]
    • allNum[1]
    • allNum[2]
    • allNum[3]
    • allNum[4]

    Since you'll want to store values at positions allNum[1] to allNum[100], how do you think you should initialise the array?

    Finally, to print out the number of occurrences for each input number, all you need is a for loop:
    		for (int i = 1; i <= 100; i++) {
    			// print out value from allNum using 'i' as the array index
    		}

  15. #15
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    Alright, so I have it mostly working now. But, now I'm trying to make it so that when I print out the concurrences, that if there was more than 1 of a number, that it would print out 'times' instead of 'time'. And is there a way that I could just print out the numbers that were inputted instead of printing out all 100 counts? Here's what I have now.
    	//scanner/values
    		Scanner input = new Scanner(System.in);
    		int number = 100;
     
    	//array
    		int[] allNum = new int[number];
     
    	//for loop, user input
    		for(int i = 1; number != 0; i++) {
    			System.out.print("Please enter integers from 1 to 100, enter 0 when finished: ");
    				number = input.nextInt();
    			allNum[number]++;
    			}
    		//printout
    		for(int j = 0; j <= 101; j++) {
    			if (allNum[number] == 1) {
    				System.out.println(allNum[j] + " time.");
    			}
    			else System.out.println(allNum[j] + " times.");
     
    		}
    	}
    and also, there's this error at the end which I tried getting rid of by increasing the 'j int' by 1, so it would be 101, but that didn't help.
    java.lang.ArrayIndexOutOfBoundsException: 100
    	at occurrence.main(occurrence.java:27)

  16. #16
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    Almost there...

    Quote Originally Posted by Elyril View Post
    And is there a way that I could just print out the numbers that were inputted instead of printing out all 100 counts?
    That's just a matter of adding an if test in the second for loop (j) to check if the allNum[number] value is 0:
    if (allNum[number] == 0)

    If the value of allNum[number] is 0, then use the continue keyword to skip to the end of the iteration to start the next iteration of the loop. See Branching Statements (The Java™ Tutorials > Learning the Java Language > Language Basics).

    Quote Originally Posted by Elyril View Post
    and also, there's this error at the end which I tried getting rid of by increasing the 'j int' by 1, so it would be 101, but that didn't help.
    The problem is still with the initialisation of the allNum array:
    Quote Originally Posted by Elyril View Post
    		int number = 100;
     
    	//array
    		int[] allNum = new int[number];
    (Be aware that int[] allNum = new int[100]; initialises the array to a size of 100. The int[100] part does not mean that the highest index of the array is 100!)

    Since this initialises the array to a size of 100, the indices that you can use in the array is from allNum[0] to allNum[99]. In other words, the highest index you can use in an array is always 1 less than the size of the array set during initialisation because an array's index starts from 0. So, when the second for loop (j) iterates to 100, the j value of 100 is inserted into allNum (allNum[100]), and this causes the ArrayIndexOutOfBoundsException.

    Recall that we're using the array's indices to store the numbers that are entered by the user (and the array's values for the amount of each number entered), and that the valid input numbers are from 1 to 100, the highest index for the allNum array is therefore 100 (i.e., allNum[100]). In order to be able to write and read values to and from allNum[100], this array will need to be initialised to a size of 101. (Remember, highest index is 1 less than the size of the array.)

    Once you have initialised the allNum array as such, the second for loop (j) should therefore be
    for (int j = 1; j <= 100; j++)
    in order to print out the values from allNum[1] to allNum[100]. Note that allNum[0] is not used.

    The main takeaways:
    1. The highest index of an array is always 1 less than the size of the array.
    2. Use the continue keyword to skip to the next iteration in a loop.

  17. The Following User Says Thank You to jashburn For This Useful Post:

    Elyril (March 19th, 2014)

  18. #17
    Member
    Join Date
    Feb 2014
    Posts
    58
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Counting input array

    Alright, I mostly got this.. except, that I'm not sure I'm using continue in the right way. And it's also not printing out 'times' if there's more than 1 count of a number. But this is what I have for my print out loop.
    for(int j = 1; j <= 100; j++) {
                            if (allNum[number] == 0) {
    				continue;
    			}
    			if (allNum[number] == 1) {
    				System.out.println(j + " shows " + allNum[j] + " time.");
    			}
    			else if (allNum[number] > 1) {
    				System.out.println(j + " shows " + allNum[j] + " times.");
    			}			
    		}

  19. #18
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Counting input array

    For this last bit it's just because the for loop uses j
    for(int j = 1; j <= 100; j++) {
    but the if tests use number as the index
    if (allNum[number] == 0) {
        ...
    }
    if (allNum[number] == 1) {
        ...
    }
    else if (allNum[number] > 1) {
        ...
    }
    and the body of the if blocks use j for the array index, e.g.,
    System.out.println(j + " shows " + allNum[j] + " times.");

    Since you're interested in checking the values stored in the allNum array from indices 1 to 100 (as in the for loop), you obviously will need to use allNum[j] in the if tests as j is what you're using in the for loop.

Similar Threads

  1. Number Counting Array issues
    By compileDammit in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 25th, 2013, 08:12 PM
  2. Array counting problem
    By Variumzky in forum What's Wrong With My Code?
    Replies: 8
    Last Post: August 2nd, 2013, 12:24 PM
  3. Counting and comparing elements in an array
    By TheBestGame in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 31st, 2012, 05:05 AM
  4. counting the values in input file and and writing the output to a file
    By srujirao in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 8th, 2012, 02:48 PM
  5. Program help with counting even and odd integers in input value.
    By fueledbyrick in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 6th, 2010, 07:02 PM

Tags for this Thread