0

我不确定为什么会遇到这个问题。但基本上我正在改组一个单词,并且我正在使用带有循环的 arrayList。

这是我的代码,出于调试目的,我添加了几行代码。

//Declare and Initialize an arrayList for character checking
      ArrayList<Boolean> jumbleVerfiy = new ArrayList<Boolean>();
      for(int x = 0; x < chosenWord.length(); x++)
          jumbleVerfiy.add(false);

      while((chosenWord.length()) != (jumbledWord.length()))
      {
          //Generate random number for getting the random character
          int verficationNumber = rnd.nextInt(chosenWord.length());

          //Checks if the random number generated has been used before
          if(jumbleVerfiy.get(verficationNumber) == false)
          {
              //Get the character from the randomly generated number and change the boolean array to keep track of
              //letters used
              jumbledWord += chosenWord.charAt(verficationNumber);
              System.out.print(jumbleVerfiy.get(verficationNumber) + " " + verficationNumber);//debug
              jumbleVerfiy.add(verficationNumber, true);
              System.out.println(" " + jumbledWord + " " + jumbleVerfiy.get(verficationNumber));//debug
          }

我的输出如下

false 3 r true
false 4 ry true
false 2 ryr true
false 1 ryra true
false 4 ryray true
tarry ryray

在此输出中,4 在第二次运行时更改为 true,但是当它循环时,由于某种原因它被设置为 false。所以我不断收到一封重复的信。我不确定问题是什么。会喜欢一些见解。

谢谢,

4

5 回答 5

2

You are adding values to the list, not setting them:

jumbleVerfiy.add(verficationNumber, true);

This means that if you for example first choose the second letter and then the second, the list ends up looking like (T,F,T,..) as if you had chosen the first and the third.

You need to use:

jumbleVerfiy.set(verficationNumber, true);
于 2013-10-04T06:02:28.443 回答
1

In your loop you are mistakenly adding a new value to the array when you should be setting a value. The offending line:

jumbleVerfiy.add(verficationNumber, true);

Which should be calling set(index, value) instead. This should resolve your problem. You also might think of using a array instead of an ArrayList to avoid the overhead associated with the ArrayList since you don't need to expand once it's been initialized.

That would be:

boolean[] jumbleVerify = new boolean[chosenWord.length()];
于 2013-10-04T06:04:37.763 回答
0

In your code you need to use

jumbleVerfiy.set(verficationNumber, true);

other it will just get added to the arrayList

于 2013-10-04T06:02:20.510 回答
0

Because you setted new item to arraylist with index( add(index, value) ). If you set item ex. index 3, then index 3 old item went to be index 4.

于 2013-10-04T06:03:52.703 回答
0

I think your problem is that you are using:

jumbleVerfiy.add(verficationNumber, true);

which adds value on position. Use following instead and should work:

jumbleVerfiy.set(verficationNumber, true);
于 2013-10-04T06:05:19.003 回答