【问题标题】:java Random String With Exclusionjava随机字符串排除
【发布时间】:2014-11-14 13:36:45
【问题描述】:

我在java中创建了这个方法来获取随机字符串:

public String getRandomStringWithExclusion(int array_id, String... exclude) {

    String[] myResArray = getResources().getStringArray(array_id);
    int idx = new Random().nextInt(myResArray.length);
    String random = (myResArray[idx]);

    for (String ex : exclude) {
        if (random.contains(ex)) {
            Toast.makeText(getBaseContext(), "fail", Utils.duration).show();
            break;
        }

    }

    return random;
}

但是当我打电话时:
getRandomStringWithExclusion(R.array.test, “测试一个”);它返回排除的值。 怎么解决?

我不是java专家。我是初学者。感谢

【问题讨论】:

  • 嗨,你的意思是 random = "test a" 结尾吗?没有任何意义,因为您没有在任何地方修改 random ,所以如果它首先被设置为排除值,那么它将保持原样?
  • 我假设您想从myResArray 返回一个随机值,但不能包含在exclude 的数组中,对吧?
  • 仅通过示例代码很难判断您要实现的目标。可以肯定的是,尽管包含检查,random 值仍不受方法影响地返回。
  • 而不是 break 我放了 getRandomStringWithExclusion(array_id, exclude) ?? @gtgaxiola 是的,对

标签: java android string random


【解决方案1】:

这是一种方法,但肯定不是最优化的:

要点是,如果您的random 字符串包含在exclude 中,那么您必须选择另一个random 并重新开始检查。

public String getRandomStringWithExclusion(int array_id, String... exclude) {
    String[] myResArray = getResources().getStringArray(array_id);
    int idx = new Random().nextInt(myResArray.length);
    String random = (myResArray[idx]);
    boolean keepGoing = true;
    while (keepGoing) {
        //Making keepGoing be false (terminating condition),
        //And only making true if the random word fails because it has to be excluded
        keepGoing = false;
        for (String ex : exclude) {
            if (random.contains(ex)) {
                Toast.makeText(getBaseContext(), "fail", Utils.duration).show();
                keepGoing = true;
                //looking for another random word
                idx = new Random().nextInt(myResArray.length);
                random = (myResArray[idx]);
                break;
            }
        }
    }
    return random;
}

【讨论】:

    【解决方案2】:

    您仍然收到您的吐司消息,是吗? 所以你的代码工作正常。

    如果你发现了返回的行为,你没有对它做出反应(意思是:无论你发现了什么,你都会重新运行它)。 而不是中断使用:

    return "";
    

    这将停止搜索更多限制并返回没有任何结果的方法。

    您好。

    【讨论】:

    • 我需要一个值。不是“”结果
    • 对不起,没有抓住这一点,只是尝试在这一点上使用递归。 'return getRandomStringWithExclusion(array_id, exclude)' 应该可以正常工作,而不是 'return ""'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多