开发者

going through an array of strings and printing one and then calling the method and printing the next one

开发者 https://www.devze.com 2022-12-17 03:52 出处:网络
I\'m trying to go through an array of strings and print one index at a time, but when I tried running the program all I get is a 0 or 1. I\'m not really sure how to fix this. Below is what I have so f

I'm trying to go through an array of strings and print one index at a time, but when I tried running the program all I get is a 0 or 1. I'm not really sure how to fix this. Below is what I have so far.

So when I call on the method I've created for this, I would like to call "Turnip" and when I call it again I get "Little Old Lady". I'm not really sure how to go about doing this, but if someone could try and fix my code I would be very thankful.

String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
int currentJoke = 0;

//while (name.equalsIgnoreCase("yes")开发者_如何学Go) {
    String temp = clues[0];
    for (int i = 0; i < clues.length - 1; i++) {
        clues[i] = clues[i + 1];
    }
    clues[clues.length - 1] = temp;
    out.println(currentJoke++);
//}


in your program it looks like you are printing currentJoke++ instead of clues[currentJoke++], probably a typo.

you can make clue a property of a class and print clues[clue++] each time the function is called...

class Clues
{
  static int clue = 0;
  static String list[] = {"Turnip", "Little Old Lady", "Atch", "Who", "Who"};

  public static void print()
  {
    if (clue > list.length - 1) clue = 0;
    System.out.println(list[clue++]);
  }

  public static void main(String[] args)
  {
    for (;;) {
      Clues.print();
    }
  }
}

you could unstatic them if you want to keep around a clues object or have multiple instances...


Not sure if yours is a homework question intended to make one learn about Java arrays. In general (when you are using Java 1.5 or above) it is recommended to use Lists instead of arrays. Here is the version of code that achieves what you need using a List.

public class Clues implements Iterable<String> {
    private final List<String> clueList;

    Clues(final String list[]) {
        clueList = Arrays.asList(list);
     }

    public Iterator<String> iterator() {
        return clueList.iterator();
    }

    public static void main(final String[] args) {
        String list[] = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
        Clues myClues = new Clues(list);
        for(String c:myClues) {
           System.out.println(c);
        }
    }
}

0

精彩评论

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