英文:
Is there a way for a program to create a new int dynamically?
问题
有没有办法让程序生成一个随机字符串,然后使用该字符串创建一个整数?我需要无限数量的整数,所以我不能在代码中精确地定义它们,然后单独为每一个写入引用。我的程序旨在简化硬币的计数和分类工作。思路是你输入一个年份,表示硬币的铸造年份,然后程序会将该年份的硬币总数加1。显然,如果你在计算和分类硬币,你不会知道每一年有多少个,所以我不能在代码中分配这个数量。我需要程序接受用户输入的每个年份,并将每个不同的年份分配给一个新的整数。然后,我需要它跟踪每个年份被输入的次数。当用户表示他们完成时,它将显示每年的小计以及所有年份的总计。
例如,用户输入2000年,程序创建int year1=2000,one=1;
。然后,用户输入1985年,程序将此值与其他任何值进行比较,由于它不同,它会创建int year2=1985,two=1;
。当用户再次输入其中一个年份时,它必须将该年份的总数加1,这意味着输入2000年将导致执行one++;
。我不能自己在代码中编写这个,因为可能包括数百个不同的年份,或者可能有两个年份。
(Note: I've left the code parts unchanged as requested.)
英文:
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.
答案1
得分: 0
以下是翻译好的内容:
你要寻找的数据结构是 Map
。Java 在开箱即用情况下提供了几种实现。例如,可以看看 HashMap<String,Integer>
。
英文:
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>
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论