• Post Reply Bookmark Topic Watch Topic
  • New Topic

Populate Array or list dynamically  RSS feed

 
Jason C Williams
Greenhorn
Posts: 13
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologize in advance if this has already been answered, when I was searching I couldn't find anything similar. I am needing a way to add to an array or list dynamically if possible. For example: The variable guesses changes when ever a user tries to guess a random number. When the correct number is guessed, the program tells the user how many guesses it took to get the right answer. This is working fine for me. I need something that will insert that value into an array or list, then, move to the next index to insert the next value and so on. I have tried this, but if I am understanding correctly, it is just entering the number of guesses the number of times in the list.

If it took the user three times to guess the code, this is the output:
Elements of ArrayList of Integer Type: [3]
Elements of ArrayList of Integer Type: [3, 3]
Elements of ArrayList of Integer Type: [3, 3, 3]
I have also seen that arrays have to have a set amount of entries set when they are created. Is there any way to do what I am trying to do, or do I need to try something else? I am extremely new to JAVA, so any help is appreciated.

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason,
It's hard to search for concepts. The word you want is "ArrayList" which is like an array that resizes as you add elements to it.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know you are told to comment your code, but the number of comments you have look s like overkill to me. Only use // comments if you are appending the comment to the line end; those comments must be short to avoid long lines. Otherwise use /* comments */ And there is no need to tell us that a variable called count counts things, nor that System.out.println("Enter next guess:"); asks for the next guess. Let's see what your code would have looked like minus the many comments, plus a few extra new lines to aid legibilityYou have some inconsistent indentation which makes it difficult to see where your loop finishes, but that error only become obvious when you reach the end of the method and see the } isn't back on the left. You may be using the wrong editor for coding; search my posts for “devent text editor” and you find some features I recommend. In this case try Notepad++ and enable its automatic indentation feature and automatic conversion of 1 tab → 4 spaces.
Don't use \n unless somebody tells you they want the LF character. Find out about the %n tag and System.out.printf instead. Don't use System.out.println(""); to go onto an new line. Use System.out.println(); instead.

Why are you calling this method recursively?
You have repeated code; lines 30 and 22 (my lines 10 and 14) should be moved after the loop.

I think Jeanne has already given you the answer to what can enlarge dynamically to accommodate any number of guesses: a List. Don't declare it as ArrayList but as List. If you are using a recent version of Java® you don't need to write Integer twice:-
List<Integer> numbers = new ArrayList<>();
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know there are a ton of comments, I am still learning and this is an assignment I am working on for my class and we have to comment everything to be able to get a decent grade. Thank you guys for the info, I am working on using a List<Integer> to do what I need. I appreciate the help Campbell Ritchie, I will move things around in my code as well. I have used Java some before, but I still have a lot to learn.
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried a for loop, but it will either add just int to the list, or multiple for the size of the int listSize. Here is the code I am using.
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason,

I am reading your initial question you started the thread with, and I cannot figure out fully your actual goal. Please clarify, so we could help you.

1. Do you need to record all guesses, no matter they are correct or not?
2. Or you need only to tell the number of guesses were made in order to guess number correctly?
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:Hi Jason,

I am reading your initial question you started the thread with, and I cannot figure out fully your actual goal. Please clarify, so we could help you.

1. Do you need to record all guesses, no matter they are correct or not?
2. Or you need only to tell the number of guesses were made in order to guess number correctly?



I am needing to record the number of guesses it took to guess the number saved into a list in individual indexes. So each one is saved to the list separately. So, if it took 2 guesses the first time, 5 guesses the next time, 10 guesses the next time, etc it would show as [2, 5, 10, etc]. After they decide not to play anymore I will use the max number from the list for another part of the program.
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Jason, I'll try to describe in english what you explained to me, and you try to tell me if it is sounds correct.

Jason C Williams wrote:I am needing to record the number of guesses it took to guess the number saved into a list
So, you need to add the number to the list before you guess what that number could be. Lets assume you added it and trying to guess. And it took you 4 attempts to guess correctly.

1. What happens with that number 4? You print it out or you need to record it somewhere?
2. What happens next when do whatever it was above in 1st part. You add another number to the list and try to guess it again as you did in 1st step?

=Jason C Williams wrote:After they decide not to play anymore I will use the max number from the list for another part of the program.
Max number.

3. Which max number? The one was added to the list as a number to be guessed, or max number of attempts it took to guess? - if latter, you need not just record, but also store them somewhere too.

As you see, problem still does not sound super clear, that is why probably you don't know how to solve it yet.
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:Ok Jason, I'll try to describe in english what you explained to me, and you try to tell me if it is sounds correct.

Jason C Williams wrote:I am needing to record the number of guesses it took to guess the number saved into a list
So, you need to add the number to the list before you guess what that number could be. Lets assume you added it and trying to guess. And it took you 4 attempts to guess correctly.

1. What happens with that number 4? You print it out or you need to record it somewhere?
2. What happens next when do whatever it was above in 1st part. You add another number to the list and try to guess it again as you did in 1st step?

=Jason C Williams wrote:After they decide not to play anymore I will use the max number from the list for another part of the program.
Max number.

3. Which max number? The one was added to the list as a number to be guessed, or max number of attempts it took to guess? - if latter, you need not just record, but also store them somewhere too.

As you see, problem still does not sound super clear, that is why probably you don't know how to solve it yet.


The best way I know to show it is like this: first game it took 2 guesses to guess the right number, the second game it took 3 guesses to guess the number, the third game it took 1 guess. So they would be in to the list like this: 2 3 1 and keep adding to the list as long as the user decides to keep playing. When the user quits playing, I need to get the highest number from the list, in this case it would be 3. Make a little more sense that way?
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One bit of feedback: give the list a better name to represent what you are storing in it.
test is not a good name :-)

Having said that, here is an example of how to use a list.


This would result in the list test to have the values [2, 3, 1] in it.
You don't need a loop to add items into the list. You just need to call the add method.


Find the right place (within your existing code) to
- Declare and initialize the list so that it gets set up once, and stays there for the whole game
- add the number of guesses it took the user to get the number into that list.


You will need a loop to go all the elements in the list and find the "maximum"

Using a standard for loop:



But rather than using a standard for loop, you could instead use one that iterates directly over the list:




That code is getting long enough that it would benefit from being broken up into more easily manageable sections
Personally I would like to see a method like

 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stefan Evans wrote:One bit of feedback: give the list a better name to represent what you are storing in it.
test is not a good name :-)

Having said that, here is an example of how to use a list.


This would result in the list test to have the values [2, 3, 1] in it.
You don't need a loop to add items into the list. You just need to call the add method.


Find the right place (within your existing code) to
- Declare and initialize the list so that it gets set up once, and stays there for the whole game
- add the number of guesses it took the user to get the number into that list.


You will need a loop to go all the elements in the list and find the "maximum"

Using a standard for loop:



But rather than using a standard for loop, you could instead use one that iterates directly over the list:




That code is getting long enough that it would benefit from being broken up into more easily manageable sections
Personally I would like to see a method like



Thank you. Test is just the name I gave it while playing around with it trying to get it to work lol. I know I can use .add(int) to get the values in the list, and it works when I put the variable in there, but it only saves the current value. As soon as another game is played, the value changes to the new value entered. So say the person took 10 guesses to guess the correct number in the first game, the value of guesses becomes 10 and it will write 10 to the list. When the person plays a second game, and takes 5 guesses to get the number right, the value of guesses changes to 5 and overwrites 10 that was saved. I need it to move to a different position in the list so it will save both values and not have one overwrite the other.
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As exhibited from my example code, calling add should NOT overwrite any existing values, but merely as the method states "add" it to the end of the list.
Can you post your latest code utilizing this for a review?

I'll repeat what I said earlier


So question 1: Where are you declaring this list of guesses in the scheme of things? i.e. where does it declare the ArrayList called gameGuessHistory (or whatever you renamed it to from test)

question 2: When and where in your code does it get initialized? i.e. where does it call new ArrayList() ?

question 3: where in the code are you calling "list.add(guesses)" ?

hint: The new ArrayList() and the list.add call should not be next to one another...
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason C Williams wrote:The best way I know to show it is like this: first game it took 2 guesses to guess the right number, the second game it took 3 guesses to guess the number, the third game it took 1 guess. So they would be in to the list like this: 2 3 1 and keep adding to the list as long as the user decides to keep playing.
Jason C Williams wrote:I am needing to record the number of guesses it took to guess the number saved into a list

Reading this, I understand you need two lists: one for the numbers to guess, and one for the guesses it took. Is that correct? Clarify those points for yourself, so you could satisfy assignment requirements.

Jason C Williams wrote:So say the person took 10 guesses to guess the correct number in the first game, the value of guesses becomes 10 and it will write 10 to the list. When the person plays a second game, and takes 5 guesses to get the number right, the value of guesses changes to 5 and overwrites 10 that was saved. I need it to move to a different position in the list so it will save both values and not have one overwrite the other
Try not to hurry with writing the code. You could solve that earlier by understanding exercise and sequence of steps first and then translating it to Java.

Try this way:
1. Generate number to guess

2. Let user guess that number
3. Increment user's guess counter + 1
- Repeat step 2 and step 3 while step 1 and step 2 numbers are not equal

4. Add counter from step 3 to the list.
- Repeat steps 1 to 4 while user wants to play

5. Look for the biggest number in the list and print it.

Does that look correct?
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Jason C Williams wrote:The best way I know to show it is like this: first game it took 2 guesses to guess the right number, the second game it took 3 guesses to guess the number, the third game it took 1 guess. So they would be in to the list like this: 2 3 1 and keep adding to the list as long as the user decides to keep playing.
Jason C Williams wrote:I am needing to record the number of guesses it took to guess the number saved into a list

Reading this, I understand you need two lists: one for the numbers to guess, and one for the guesses it took. Is that correct? Clarify those points for yourself, so you could satisfy assignment requirements.

Jason C Williams wrote:So say the person took 10 guesses to guess the correct number in the first game, the value of guesses becomes 10 and it will write 10 to the list. When the person plays a second game, and takes 5 guesses to get the number right, the value of guesses changes to 5 and overwrites 10 that was saved. I need it to move to a different position in the list so it will save both values and not have one overwrite the other
Try not to hurry with writing the code. You could solve that earlier by understanding exercise and sequence of steps first and then translating it to Java.

Try this way:
1. Generate number to guess

2. Let user guess that number
3. Increment user's guess counter + 1
- Repeat step 2 and step 3 while step 1 and step 2 numbers are not equal

4. Add counter from step 3 to the list.
- Repeat steps 1 to 4 while user wants to play

5. Look for the biggest number in the list and print it.

Does that look correct?


That sounds right. Like I said, I can get the number of guesses into the list, I am having problems with getting the next number to go into the next position in the list and not overwriting the previous number.
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason C Williams wrote:That sounds right.
Great, one part done, we agreed on steps you need to do.

Jason C Williams wrote:Like I said, I can get the number of guesses into the list, I am having problems with getting the next number to go into the next position in the list and not overwriting the previous number.
I haven't seen your code, but the issue is partially clear. Likely you're re-initializing ArrayList each time the guess is correct. Initialize it above all loops you have. All program program structure try to build by looking at the steps you agreed as correct. If experience any problems, try to post relevant code segment, so we could see where the logic flaws.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason C Williams wrote:That sounds right. Like I said, I can get the number of guesses into the list, I am having problems with getting the next number to go into the next position in the list and not overwriting the previous number.

If you are indeed using a List, then the add() method should do that for you.

However, if you are only worried about the most number of guesses the player took, do you really need a list?

Assuming the number is held in a field called 'maxGuesses', the logic might be as simple as:
HIH

Winston
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Jason C Williams wrote:That sounds right.
Great, one part done, we agreed on steps you need to do.

Jason C Williams wrote:Like I said, I can get the number of guesses into the list, I am having problems with getting the next number to go into the next position in the list and not overwriting the previous number.
I haven't seen your code, but the issue is partially clear. Likely you're re-initializing ArrayList each time the guess is correct. Initialize it above all loops you have. All program program structure try to build by looking at the steps you agreed as correct. If experience any problems, try to post relevant code segment, so we could see where the logic flaws.


Here is what I have:



It writes to the list and moves to the next available index, but it prints the same number in the list. For example: if the number of guesses for the first game is 5, it will put 5 in the first slot like this [5]. When another game is played and the amount of guesses is say 2, it will put it in the second slot, but overwrites the 5 that was there before like this [2, 2]. If I leave out the maxGuesses[i] = guesses; it will write zero to the list every time it runs since there is nothing to put a value in the slot. I think I know what the problem is, it is overwriting the guesses with the next amount of guesses number because it is calling guesses again as the input. Is there a way around is this that I am missing?
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No no Jason, wait, there is something surely wrong, it seems you're not following the steps you agreed before. Remember, array is not re-sizable, and what you're sort of trying to do, is to create an array of size of guesses, it is even difficult to tell what actually you're doing in that code as logic flaws in couple of places.
By the way, look at Winston's nice approach, you wouldn't need to use even ArrayList for that, unless it is your assignment requirement. Double check that in exercise requirements.

Let me try to show you once again in pseudo code what you're likely intended to do:

Winston's suggested solution is more elegant, but it wouldn't allow you to check smallest guesses number, maybe average guesses it takes and similar, but you need to double check that, maybe it is on requirements maybe it is not, we don't know that.

Is it clearer?
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston's solution does make sense, but I still run into the issue of storing the amount of guesses somewhere to compare against the current amount of guesses
 
Liutauras Vilda
Sheriff
Posts: 4914
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But I just wrote you a full pseudo code for you how your program could be looking like, you just need to translate it to Java. Have you tried? Show us the code please and tell which part you cannot understand.
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I swear that pseudo code was not there when I last replied. I'll try it when I get home from work.
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not have to use a list, I thought it might be easier to do what I wanted to do, but is turning into a nightmare. I am making this much harder than it has to be. I've tried everything with a list and on here, and I still cannot make it do what I want no matter what I try. All I need is for the program to save the first # of guesses then compare it to all the other guesses made until the user stops playing. I know I can use Math.max() to compare the values while it is running to save the max number from the two. I am lost on how to save the first amount of guesses somewhere where it will not change while the other is looping through.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lists are easy to use. You can create a List
List<Foo> fooList = new XYZList<>();
… and add to it
fooList.add(new Foo(...));
… and print it out
System.out.println(fooList);
Of the different types of List, this is the most popular type by far.
 
Jason C Williams
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fig it out. I declared the List<integer> list = new ArrayList<>(); at the top with the variables. Added the list.add(guesses); at the bottom of the guess number method. In the last method, I sorted the list from largest to smallest and picked the first number in the list.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply searching for the maximum is faster than sorting. A linear search runs in linear time and the fastest sorting algorithms run in nlongn time. If you use Java8 you can probably get a Stream to do all the work for you.All Lists have a stream() method (actually inherited from Collection), which returns a Stream object, which will do all the iteration for you. A Stream can have its maximum value found if you pass a Comparator. The compiler “knows” it is looking for a Comparator, so I told it to look in the Integer class and find the (static) compare method. It can use the compare method to construct something which behaves like a Comparator<Integer> but without creating the anonymous class. The max method returns an Optional (in this case an Optional<Integer> whose get() method returns an Integer. If you have an empty Stream (i.e. the List started off life empty), the Optional will be empty too and the get method will throw an Exception.

You can probably sort that out with its ifPresent and orElse methods.

There are all sorts of other ways to do it. You can change the Stream<Integer> to an IntStream for example, whose max method does not require a Comparator.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote:. . . the fastest sorting algorithms run in nlongn time. . . .
Slap wrist. Naughty boy, Campbell. That is of course nlogn time.

Look up the orElse() method, and you find that version will return 0 from an empty Stream.
 
Shawn Lau
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm think the OP wants a game history and an array list would work fine for that.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. I shall be more specific; he wants a java.util.ArrayList. There are other versions of ArrayList; some methods (I think this one) return an ArrayList but it is a different ArrayList. I did try getting a List from the collect(Collectors.toList()) method call on a Stream and tried getClass().getName() onit. That printed java.util.ArrayList. But it is still better simply to call it a List and program to its interface.

At this stage, I think OP has already got the List working, but I thought he had an inefficient way to get the maximum out of the List, so I tried a new way. And learnt about the orElse method mentioned above in the process
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!