Skip to content
Advertisement

Is there a way for a program to create a new int dynamically?

Is there a way to have a program generate a random string and then create an int using that string? I need an indefinite number of int, so I can’t exactly define them all in the code and then write in references to them each individually. My program is meant to be a simple aid in counting and cataloging coins. The idea is you enter a year, meaning the year the coin was minted, and the program adds 1 to the tally of coins from that year. Obviously, if you’re counting and cataloging coins, you don’t already know how many of each year you have, so I can’t assign that in the code. I need the program to take each year that the user inputs and assign each different year to a new int. I then need it to keep track of how many times each year was entered. When the user indicates they are finished, it will then display the subtotals for each year and an overall total for all years.

For example, the user enters 2000 and the program creates int year1=2000,one=1;. Then, the user enters 1985, the program compares this value to any others, and since it is different then it creates int year2=1985,two=1;. When the user enters one of these years again, it must add 1 to the tally for that year, meaning entering 2000 will cause it to do one++;. I cannot write this in the code myself because there could be hundreds of different years included or there could be two.

Advertisement

Answer

The data structure you are looking for is a Map. Java provides several implementations out of the box. Look for example at HashMap<String,Integer>.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement