【发布时间】:2014-03-03 10:57:40
【问题描述】:
我有一组代码,目前使用的是由数字组成的 30 个手动输入字符串的预设列表,如下所示:
String[] elementsToAdd2 = { "100", "510", "170", "214", "268", "398",
"235", "802", "900", "723", "699", "1", "16", "999", "890",
"725", "998", "978", "988", "990", "989", "984", "320", "321",
"400", "415", "450", "50", "660", "624" };
我想用其他可以产生任意数量的随机字符串数字的东西替换它,在某个预设大小之间。我的想法是使用以下代码代替它:
public class HashFunction {
.
.
.
private Random r = new Random();
public String randomString(int limit)
{
int n = r.nextInt(limit);
return n+"";
}
.
.
.
public static void main(String[] args) {
HashFunction theFunc = new HashFunction(30); // this is where you can control the number of spaces in the hash table!!!
String[] elementsToAdd2 = new String[30];
for (int i = 0; i <= elementsToAdd2.length; i++)
{
String[i] elementsToAdd2 = randomString(1000);
}
当我读到这篇文章时,我认为它的意思是“i”处的数组字符串值将被分配给介于 0 和 1000 之间的随机值。但是,我收到一条错误消息。它说一个“;”意料之中,而且我有不兼容的类型。我认为 Java 正在读这个说我试图设置一个字符串数组等于单个字符串,即使我在 "String[i]" 中包含了 "i" 以指定在数组中放置值的位置。
如果有人可以帮助我理解我的问题,请告诉我。谢谢!
附言此代码创建哈希表,以防与我遇到的问题相关。如果您愿意,我可以提供代码,但我想隔离问题并仅显示与之相关的内容。
【问题讨论】:
-
不是
String[i] elementsToAdd2 = ...,而是elementsToAdd2[i] = ...。并且循环不应在i <= elementsToAdd2.length时运行,而应在i < elementsToAdd2.length时运行。