• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with randomizing a String Array.  RSS feed

 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I'm writing a simple game and I'm trying to randomize a string array. Trouble is I'm not sure about the general structure of the program. I construct 2 string arrays which are displayed as dialog drop down boxes. I would like the order of the array to be different each time the program is called.

At the moment the structure is

String [] string1= { ....}
string1.randomize();

String[] string2= {....}
string2.randomize();
....
public void randomize()

// swap strings in the array in a random way then return the string array

The questions I have are can I use the randomize function for both string arrays? Do I need to refer the the string arrays in the randomize function as "this"? Also is this general structure of the program correct? I am updating and adding this feature onto a Swing program that was working before I made the changes.

Many thanks for your help.

Regards
Bill
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly do you mean by "randomize"? Do you want to put the strings in the array in a random order, in other words, you want to shuffle the array? Java has a method for that: Collections.shuffle

Note that it takes a List<?> instead of an array, but you should be able to call it by wrapping your array as a list: Collections.shuffle(Arrays.asList(string1));
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry ... I'm new to Java and I have read about wrapping as an object but I don't think I understand it yet. I tried to put your code into my program by calling an object that I had set to your object .. I needed to declare a new object and I don't know what to declare that as. List ? Arraylist? Nothing I tried worked.

Regards
Bill
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Jillians wrote:Sorry ... I'm new to Java and I have read about wrapping as an object but I don't think I understand it yet. I tried to put your code into my program by calling an object that I had set to your object .. I needed to declare a new object and I don't know what to declare that as. List ? Arraylist? Nothing I tried worked.



Jesper's code assumes that you have a String array -- as you have created in your first post. Don't know what you mean by "I needed to declare a new object and I don't know what to declare that as".

Henry
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry ... I meant I had to declare a list object that I could set equal to the collections.shuffle code Jesper gave me. So I need to declare this list object as an object of a particiular type. For example

List (?) obj= new list (?)
obj=collections.shuffle(...)

I don't know what the class of the object obj is to declare it properly.

Regards
Bill
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Jillians wrote:Sorry ... I meant I had to declare a list object that I could set equal to the collections.shuffle code Jesper gave me. So I need to declare this list object as an object of a particiular type. For example

List (?) obj= new list (?)
obj=collections.shuffle(...)

I don't know what the class of the object obj is to declare it properly.


Perhaps the Sun/Oracle tutorial on collections is a good place to start...

http://docs.oracle.com/javase/tutorial/collections/index.html

Henry
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ... I've read the relevant parts of that section.

I have adjusted my code as follows for a random array of selected countries.

public class CountryCapitals {


public static void main(String[] args) {
public interface List<E> extends Collection<E> {
//Using a String array for the countries to be used as the
//selection options by the input dialog box
String[] countriesTemp = {"China", "Ethiopia", "Italy", "Haiti", "Luxembourg", "Malta", "India"
, "Pakistan", "Japan", "Russia", "Serbia", "Portugal", "Spain", "Turkey", "Uganda"
, "Norway", "France", "Germany", "USA", "Mexico", "Canada", "Brazil", "Sweeden"
, "Israel" };
List<String> list = Arrays.asList(countriesTemp); // transfer from array to list
Collections.shuffle(list); // shuffle list
String[] countries = list.toarray(); // back to an array

I think I have to implement the Collections interface somehow as at the moment the compiler doesn't recognise List. I'm not sure if I need to import something to make this work.

Any more clues?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Jillians wrote:Thanks ... I've read the relevant parts of that section.

I have adjusted my code as follows for a random array of selected countries.

public class CountryCapitals {


public static void main(String[] args) {
public interface List<E> extends Collection<E> {
//Using a String array for the countries to be used as the
//selection options by the input dialog box
String[] countriesTemp = {"China", "Ethiopia", "Italy", "Haiti", "Luxembourg", "Malta", "India"
, "Pakistan", "Japan", "Russia", "Serbia", "Portugal", "Spain", "Turkey", "Uganda"
, "Norway", "France", "Germany", "USA", "Mexico", "Canada", "Brazil", "Sweeden"
, "Israel" };
List<String> list = Arrays.asList(countriesTemp); // transfer from array to list
Collections.shuffle(list); // shuffle list
String[] countries = list.toarray(); // back to an array

I think I have to implement the Collections interface somehow as at the moment the compiler doesn't recognise List. I'm not sure if I need to import something to make this work.

Any more clues?


You need to import the classes that you are using -- which includes List, Arrays, Collections, etc. The compiler only implicitly imports classes from the same package as the class to be compiled, and from the java.lang package.

Henry
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Bill Jillians wrote:Sorry ... I meant I had to declare a list object that I could set equal to the collections.shuffle code Jesper gave me. So I need to declare this list object as an object of a particiular type. For example

List (?) obj= new list (?)
obj=collections.shuffle(...)

I don't know what the class of the object obj is to declare it properly.


Perhaps the Sun/Oracle tutorial on collections is a good place to start...

http://docs.oracle.com/javase/tutorial/collections/index.html

Henry


Well I'm afraid I've read this several times now. What it doesn't tell me is context. For instance I realize that List<E> is generic notation (as is presumably List<?> used above). It doesn't tell me where this class is located so I can import it (I am just starting to get a handle on the JavaDoc notes but I can't say I am particularly au fait with them at the moment. ) Its a lot of information to take in and I am having problems digesting it. I've bought Horsmann and Cornell vol 1 and have been reading that to help pad out my ignorance. Sadly they don't mention collections in that volume.

My impulse at the moment is to scrap this shuffle method and to stick with what I understand which would be to write my own shuffle method and wait until I am more familiar with collections before I implement them.

Sorry for being so dense.

Regards
Bill
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Horstmann and Cornell? Excellent book
The Java™ tutorials do go quickly sometimes. It should have told you the difference between sets, lists queues and maps on this page. Did you understand that bit?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Jillians wrote:My impulse at the moment is to scrap this shuffle method and to stick with what I understand which would be to write my own shuffle method and wait until I am more familiar with collections before I implement them.

Don't. That's a very bad way to start your education in an Object Oriented language, because the whole point of them is to build on previous knowledge (don't re-invent the wheel).

My tip: ALWAYS, ALWAYS, ALWAYS have a copy of the Java API documentation open on your desktop when you're programming; no matter how trivial you think it is. I've been doing this for 35 years (about 12 with Java) and I rarely forget (unless me Alzheimer's kicks in).

Then, you're but a few clicks away from your class definition; and right at the top it gives you the complete path that you need for an import statement.

Winston
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Horstmann and Cornell? Excellent book
The Java™ tutorials do go quickly sometimes. It should have told you the difference between sets, lists queues and maps on this page. Did you understand that bit?


Yes I do understand that. Sets don't repeat elements, lists can repeat elements and have an ordering which is something I want to change. Maps are one to one representations. Queues order things first in first out.
 
Bill Jillians
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Bill Jillians wrote:My impulse at the moment is to scrap this shuffle method and to stick with what I understand which would be to write my own shuffle method and wait until I am more familiar with collections before I implement them.

Don't. That's a very bad way to start your education in an Object Oriented language, because the whole point of them is to build on previous knowledge (don't re-invent the wheel).

My tip: ALWAYS, ALWAYS, ALWAYS have a copy of the Java API documentation open on your desktop when you're programming; no matter how trivial you think it is. I've been doing this for 35 years (about 12 with Java) and I rarely forget (unless me Alzheimer's kicks in).

Then, you're but a few clicks away from your class definition; and right at the top it gives you the complete path that you need for an import statement.

Winston


Thanks for the link. I'll familiarize myself with that page as an important priority.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are at least three ways you can change the ordering of a List
  • 1: Insert or remove elements by calling methods.
  • 2: Sort the List. This does require certain properties in the elements, which you can read about in the sort() method.
  • 3: Pseudo-randomise the List with the shuffle(List) method.
  • I have just noticed other ways to alter ordering in the Collections class, which I hadn’t seen before. Have a look through its other methods.
     
    Junilu Lacar
    Sheriff
    Posts: 11494
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I don't think that going through the exercise of implementing your own shuffle method is necessarily a bad thing if you're learning how to program. It can give some pretty useful insights and create new thinking paths in the brain. That said, I'm a very lazy programmer in the sense that Winston talked about, always preferring to find something that's already been written rather than give in to the NIH siren call (Not Invented Here).
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Well I'm making progress with this. At the moment the code is

    which compiles ok up to the last line and I'm not sure what is wrong with it. The Java standard edition seems to imply the use of the toArray function is correct. The compiler stops at this line and I thought a cast might fix it but it still fails.

    Any clues on what is wrong with that last line. I can't use a list in the JOptionPane function I'm using so it has to be transfered back into and array.

    Regards
    Bill

    (Moderator edits: added code tags for readability)
     
    Junilu Lacar
    Sheriff
    Posts: 11494
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It helps if you put code tags around your code samples. Try

     
    dennis deems
    Ranch Hand
    Posts: 808
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bill Jillians wrote: which compiles ok up to the last line and I'm not sure what is wrong with it.

    Doesn't the compiler error give you an idea about what is wrong with this line?

    Variable declarations in Java follow this form: [Type] [name] = [value].
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Junilu Lacar wrote:It helps if you put code tags around your code samples. Try



    Sorry ... but surely the variable is list and toArray is a function acting on it. This needs to be set equal to the array that will hold the list values. I don't see how this improves the coding.
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dennis Deems wrote:
    Bill Jillians wrote: which compiles ok up to the last line and I'm not sure what is wrong with it.

    Doesn't the compiler error give you an idea about what is wrong with this line?

    Variable declarations in Java follow this form: [Type] [name] = [value].


    I'm using BlueJ which is a beginners compiler which seems appropriate for my skill level. It comes up with a message that there is a missing ";" in the line. Quite why it thinks this I don't know but there is obviously a problem with that line. I assume it is to do with the toArray function and the way it is used.
     
    dennis deems
    Ranch Hand
    Posts: 808
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bill Jillians wrote:
    Dennis Deems wrote:
    Bill Jillians wrote: which compiles ok up to the last line and I'm not sure what is wrong with it.

    Doesn't the compiler error give you an idea about what is wrong with this line?

    Variable declarations in Java follow this form: [Type] [name] = [value].


    I'm using BlueJ which is a beginners compiler which seems appropriate for my skill level. It comes up with a message that there is a missing ";" in the line. Quite why it thinks this I don't know but there is obviously a problem with that line. I assume it is to do with the toArray function and the way it is used.

    No, it's much simpler than that. Simple problems, I find, are the most easily overlooked. There's an extraneous element there.
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dennis Deems wrote:
    Bill Jillians wrote:
    Dennis Deems wrote:
    Bill Jillians wrote: which compiles ok up to the last line and I'm not sure what is wrong with it.

    Doesn't the compiler error give you an idea about what is wrong with this line?

    Variable declarations in Java follow this form: [Type] [name] = [value].


    I'm using BlueJ which is a beginners compiler which seems appropriate for my skill level. It comes up with a message that there is a missing ";" in the line. Quite why it thinks this I don't know but there is obviously a problem with that line. I assume it is to do with the toArray function and the way it is used.

    No, it's much simpler than that. Simple problems, I find, are the most easily overlooked. There's an extraneous element there.


    Possibly you mean I don't need the second string declaration. The compiler says incompatible types if I remove that.
     
    Paul Clapham
    Sheriff
    Posts: 22834
    43
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bill Jillians wrote:Possibly you mean I don't need the second string declaration. The compiler says incompatible types if I remove that.


    Yes, that's correct, you don't need that.

    And yes, you get an error message if you remove it. That doesn't mean that removing it was wrong. It means that you then have to carry on and fix the new error message.
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Clapham wrote:
    Bill Jillians wrote:Possibly you mean I don't need the second string declaration. The compiler says incompatible types if I remove that.


    Yes, that's correct, you don't need that.

    And yes, you get an error message if you remove it. That doesn't mean that removing it was wrong. It means that you then have to carry on and fix the new error message.


    Well it compiles with the code Junilu Lacar wrote. I haven't run it yet to see if it gives the correct answer. Also I don't really understand why it work s which may have a lot to do with my ignorance of the ToArray function or where you find that information out. I saw the toArray function on an Oracle tutorial page and it seemed to do what needed to be done. There must be a detailed source of information about functions like that and sadly I don't know where it is.
     
    Paul Clapham
    Sheriff
    Posts: 22834
    43
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bill Jillians wrote:There must be a detailed source of information about functions like that and sadly I don't know where it is.


    Oh, my. You've been trying to write Java code without looking at the API documentation? No wonder it seems like an uphill battle. API documentation is here.
     
    Junilu Lacar
    Sheriff
    Posts: 11494
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bill Jillians wrote:Well it compiles with the code Junilu Lacar wrote. I haven't run it yet to see if it gives the correct answer. Also I don't really understand why it work s

    Here's what you get from the JavaDocs:
    - List.toArray() returns an Object[]
    - List.toArray(T a[]) returns a T[], that is, an array whose elements are of the type T.

    So, if you just say list.toArray(), the compiler considers the return value as an Object[], which can't be legally assigned to a variable declared as a String[], hence the compile error: "Type mismatch: cannot convert from Object[] to String[]"

    When you say list.toArray(new String[0]), the compiler takes the "hint" to use the second form and consider the return value as a String[], which of course can be assigned to a variable declared as a String[].
     
    Bill Jillians
    Greenhorn
    Posts: 22
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you very much to everyone who contributed. The program now works just the way I would hope it would. Time to move on to the next project.

    Cheers
    Bill
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!