2014-11-14 75 views
0

我在Java中創建這種方法來獲得一個隨機字符串: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的專家。我是初學者。謝謝

+0

嗨,你的意思是隨機=「測試」結束?這是不是有意義,因爲你不隨意修改任何地方,所以如果它首先被設置爲排除值,那麼它將保持原樣? – xcoder 2014-11-14 13:47:49

+0

我假設你想從'myResArray'中返回一個隨機值,但不能包含在'exclude'的數組中嗎? – gtgaxiola 2014-11-14 13:50:18

+0

很難通過示例代碼告訴您想要實現什麼。一件確定的事情是,儘管包含檢查,「隨機」值仍然不受該方法影響。 – topr 2014-11-14 13:52:23

回答

0

這裏是一個辦法做到這一點,但肯定不是最優化:

要點是,如果你的random字符串包含withing 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; 
} 
-1

你仍然有你的敬酒信息,是嗎? 所以你的代碼工作正常。

如果你發現它,你沒有對返回的行爲做出反應(意思是:不管你發現什麼,你都會重試它)。 而不是休息使用:

return ""; 

這將停止搜索更多的限制,並沒有爲返回結果的方法。

問候。

+0

我需要一個值。不是「」結果 – user3744384 2014-11-14 14:05:31

+0

對不起,沒有采取那一點, 只是試圖在這一點上使用遞歸。 'return getRandomStringWithExclusion(array_id,exclude)'應該工作正常,而不是'return'「' – silentCode 2014-11-14 14:55:18