每次执行时都有新的字符串值

时间:2019-11-19 09:31:25

标签: java string list arraylist

有5个字符串值(列表)。每次执行代码时,它都应该选择与上一个不同的值。

2 个答案:

答案 0 :(得分:2)

您提出问题的方式并不完全适合stackoverflow,因为您要的是一种基本的技术,并且根本不提供到目前为止所尝试的内容。我还是会回答你的。

您需要将最后选择的String(或其索引,哈希,您选择的某种表示形式...)保存到文件中,然后再次执行代码时,您将选择一个随机int,检查如果File存在,并且是,则选择一个新的随机Int直到!list [random] .equals(lastString)。再次,将该字符串保存到所述文件。

此外,您需要指定再次执行代码的确切含​​义。我们是在谈论持久性或暂时性记忆吗?

答案 1 :(得分:0)

如果您的问题是可以从下面的代码中使用的,那是从同一数字“池”中获取值的方法。

import java.util.Random;
import java.util.ArrayList;

class Main {
  private static ArrayList<String> YourList = new ArrayList<String>(); // creates your List

  public static void main(String[] args) {
    for(int i = 0; i < 5; i++) {
      YourList.add(Integer.toString(i)); // fills it with random values
    }
    for(int i = 0; i < 5; i++) {
      String return_value = GetValue(); // returns the string you wanna output
      System.out.println(return_value); // output
    }
  }

  private static String GetValue() {
    Random r = new Random(); // new random created
    int index = r.nextInt(5); // get a new random index to select from your list
    String temp = YourList.get(index); // cast the valu from the list to a temp String
    return temp; // reutrn statement
  }
}

如果您不想再次使用相同的号码,则需要添加行

YourList.remove(index)

进入函数GetValue()。

并更改

int index = r.nextInt(5);

进入

int index = r.nextInt(YourList.length);

我希望这对您有帮助

相关问题