开发者

getting duplicate array output - java

Can someone could be kind and help me out here. Thanks in advance...

My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.

public class Worldcountries
{

    private static Random nums = new Random();   

    private static String[] countries =
    {
        "America", "Candada", "Chile", "Argentina"
    };


    public static int Dice()
    { 
        return (generator.nums.nextInt(6) + 1);  
    } 


    public String randomCounties()
    {
        String aTemp = " ";
        int numOfTimes = Dice();
        int dup = 0;

        for(int i=0 ; i<numOfTimes; i++)
        {
            // I think it's in the if statement where I am going wrong. 
            if (!countries[i].equals(countries[i])) 
            {
                i = i + 1;
            }
            else
            {
                dup--;  
            }

            // and maybe here  
            aTemp = aTemp + countries[nums.nextInt(countries.length)];
            aTemp = aTemp + ",";  
        }

        return aTemp;
    }
}

So the output I am getting (randomly) is, "America, America, Ch开发者_StackOverflowile" when it should be "America, Chile".


When do you expect this to be false?

countries[i].equals(countries[i])

Edit:

Here's a skeleton solution. I'll leave filling in the helper methods to you.

public String[] countries;

public boolean contains(String[] arr, String value) {
    //return true if value is already in arr, false otherwise
}

public String chooseRandomCountry() {
   //chooses a random country from countries
}

//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
    while (true) {
       String randomCountry = chooseRandomCountry();
       if ( !contains(selection, randomCountry ) {   
          selection[i] = randomCountry;
          break;
       }
    }
}

//...then build the string here

This doesn't check important things like the number of unique countries.


You need a data structure which allows you to answer the question "does it already contain item X?"

Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).


You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like

/* 
    ...
 */
bool[] printed = new bool[countries.length];

for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
      int r = nums.nextInt(countries.length);
      if (printed[r] == false) 
      {
          i = i + 1;
          printed[r] = true;
          aTemp = aTemp + countries[r];
          aTemp = aTemp + ",";  
      }
}
return aTemp;


Consider what you're comparing it to:

if (!countries[i].equals(countries[i]))

are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.

make list uniqueCountries
for each string called country in countries
    if country is not in uniqueCountries
        add country to uniqueCountries
print each country in uniqueCountries

When you do this, watch out for index out of bounds, and adjust accordingly


Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:

public String randomCounties() {
    List<String> results = Arrays.asList(countries);
    Collections.shuffle(results);

    int numOfTimes = Dice();
    String result = " ";
    for(int i=0 ; i<numOfTimes; i++) {
        result = result + countries[i] + ", ";
    }

    return result;
}


If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.

You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.

one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜