user1854291
user1854291

Reputation: 21

Java Iterate through string array and return on at a time, in loop

I've done quite a few searches on this but can only find implementations that don't apply (e.g. using random, which I already have). Pretty rookie question, any help is greatly appreciated.

I got a string array and currently I return a random one through a simple function I implemented as the onCLick value of a button, code below. So, every time someone clicks on the bottun, a new string is set.

What I want to do instead is to go through the array top to bottom, returning one string at a time, and then start over. I suspect there might be several ways to do this, any suggestions? Thanks a lot in advance!

public class FirstActivity extends Activity {

  private TextView myStringView;
  private static final Random RANDOM = new Random();
  String myString;


  //....my other code


  private static final String[] MYSTRINGS = {
      "string a",
      "string b",
      "string c"
  };

   public void generateString(View v) {

      int myStringsLength = MYSTRINGS.length;
      String myString = MYSTRINGS[RANDOM.nextInt(myStringsLength)];
      myStringView.setText(myString);

  }
}

Upvotes: 0

Views: 2225

Answers (6)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

You could write an Iterator that loops forever:

public class Test {
  public static void main(String args[]) {
    System.out.println("Test");
    new Test().test();
  }

  public void test() {
    String[] strings = {"One",
      "Two",
      "Three"};
    for (Iterator<String> s = new ArrayIterator<>(strings); s.hasNext();) {
      System.out.println(s.next());
    }
    int i = 0;
    for (Iterator<String> s = new ArrayIterator<>(strings, true); i < 10 && s.hasNext(); i++) {
      System.out.println(s.next());
    }
  }

  static class ArrayIterator<T> implements Iterator<T> {
    private final T[] array;
    private boolean loop = false;
    private int i = -1;
    private T next = null;

    public ArrayIterator(T[] array, boolean loop) {
      this.array = array;
      this.loop = loop;
    }

    public ArrayIterator(T[] array) {
      this(array, false);
    }

    @Override
    public boolean hasNext() {
      if (next == null) {
        // Step 1.
        i += 1;
        if (i == array.length) {
          if (loop) {
            i = 0;
          }
        }
        next = (i < array.length ? array[i] : null);
      }
      return next != null;
    }

    @Override
    public T next() {
      T it = next;
      next = null;
      return it;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("Not supported.");
    }
  }
}

Prints:

One
Two
Three
One
Two
Three
One
Two
Three
One
Two
Three
One

Upvotes: 0

comanitza
comanitza

Reputation: 1103

indeed there are several ways of achieving this, the best solution to your problem as I understand it is to keep a counter that represents the current String in the array reached, and return the corresponding String value, like:

String[] arr = new String[] {"a", "b", "c"};
int counter = 0;

public String getStringFromArr() {

    if(counter < arr.length) {
        return arr[counter++];
    } else {
        counter = 0;

        return arr[counter++];
    }
}

This is think it's the simplest implementation. You can further abstract away this put it in a class that takes an Array of Strings and exposes a nextString() method that returns the String to be used.

Also a good point would be to use a List instead of a String[].

You should now call getStringFromArr() from your method.

Upvotes: 0

DSJ
DSJ

Reputation: 106

You essentially want to implement a circular array. You can do this by keeping a counter in your class then:

public void generateString(View v) 
{
    int index = count % MYSTRINGS.length;
    count++;

    String myString = MYSTRINGS[index];
    myStringView.setText(myString); 
}

Upvotes: 1

entropy
entropy

Reputation: 3144

This should work:

public class FirstActivity extends Activity {

  private TextView myStringView;
  private int stringIndex;
  String myString;


  //....my other code


  private static final String[] MYSTRINGS = {
      "string a",
      "string b",
      "string c"
  };

   public void generateString(View v) {

      int myStringsLength = MYSTRINGS.length;
      String myString = MYSTRINGS[stringIndex];
      stringIndex = (stringIndex + 1) % myStringsLength;
      myStringView.setText(myString);

  }
}

Upvotes: 1

Tom
Tom

Reputation: 16188

A static counter would do the trick.

public class FirstActivity extends Activity {

  private static int counter = 0;      

  private TextView myStringView;
  private static final Random RANDOM = new Random();
  String myString;


  //....my other code


  private static final String[] MYSTRINGS = {
      "string a",
      "string b",
      "string c"
  };

   public void generateString(View v) {

      String myString = MYSTRINGS[counter++];
      if( counter == MYSTRINGS.length ) {
          counter = 0;
      }
      myStringView.setText(myString);

  }
}

Upvotes: 0

ogzd
ogzd

Reputation: 5692

Create your own function:

 private static int counter = 0;

 private int nextInt(int length) {
     return (counter++) % length;
 }

and simply call it instead of RANDOM.nextInt()

Upvotes: 5

Related Questions