tags:

views:

110

answers:

7

Hello,

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, Chile" when it should be "America, Chile".

+6  A: 

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.

Mark Peters
Mark - what I trying to say here is if they for example America string and America string have not been randomly selected then display it
All that condition is doing is seeing if something equals itself which will of course be true. Honestly, even by your comment above I don't understand what it's supposed to do.
Mark Peters
Try `aTemp.contains()` instead of `equals()`
Aaron Digulla
He tries to compare new generated string with old generated string and if they are same - skip current 'i'. But what he did is such a mess that I don't even want to rewrite it...
Max
@Aaron: That would work, though I would be shocked to see a requirement not to use a Collection.contains but allow String.contains.
Mark Peters
A: 

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

glowcoder
I need to check if whole array for a particular string has not already randomly selected. If it has selected then don't select it again. Also I cannot use HashSet or LinkedHashSet().
Can you use LinkedList? The pseudocode in the second code block will do what you'd like it to do. It's still homework after all, and I'm sort of ethically bound to not spit out Java code in this case. Besides, learning to understand pseudocode is an important part of working in the software field. :-)
glowcoder
No LinkList neither. I know how to append, sets etc.
+1  A: 

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).

Aaron Digulla
A: 

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;
}
Max
Can't use append neither. I have to hardcord the syntax
As you wish, removed the StringBuilder and now it uses 'hardcord' syntax... Check the new code.
Max
This doesn't check for duplicates. Just because you find Sets "creepy" doesn't give you license to just the main requirement ;-).
Mark Peters
Does not check for duplicates? It has no duplicates in first place! That's the beauty of this code. You just shuffle the list of countries and get as much as you need from that list.
Max
A: 

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;
Nubsis
Nubsis - I think this what I may be looking for but in else statement to used continue. I can't use continue.
Omg, you can't use continue? O_o I'm out of here.
Max
Then try moving the last block into the 'if' and leave the else empty
Nubsis
-1 for using inappropriate `continue` (think again, why exactly do you need it?). The loop may be running a long time if numOfTimes is near countries.length.
Hardcoded
Nubsis - could you explain bool[] printed = new bool[countries.length]();got error "; expected"then I tried bool[] printed = new bool[countries.length];complied but when executing got error Exception: java.lang.NullPointerExceptionthanks.
My Java-jutsu is not what it used to be. The code shows an incorrect way to initialize an array. My apologies. Try removing the parantheses. You should also be aware that this code is mostly to illustrate the solution. There is no guarrantee that the code will terminate. Make sure than you have more countries than sides on the die you roll.-- EDIT: Make sure the countries array has been initialized as well...
Nubsis
Nubsis - the code is now working. Thank you for solving the problem for me.
You're welcome. It is also customary to check the answered button ;>
Nubsis
What you mean by It is also customary to check the answered button. I cannot find a answered button. If thats what you mean?
If you take a look under the rating number for this answer, there should be an outline for a 'check'-symbol. If you click it, it will indicate that the question has been answered ^^
Nubsis
the tick has changed to green, so it should be OK.
A: 

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.

Angelo Genovese
A: 

Is this what you mean right?