2013-10-02 81 views
-4

我有這樣的事情:從字符串替換一些隨機選擇[]

import java.util.Random; 

public class gramatica { 
public static void main(String[] args) { 

    String [] Vt = {"S","R","L"}; 
    String [] Vn = {"a","b","c","d","e","f"}; 

    String [] S = { 

      "aS","bS","cR","dL" 
    }; 

    String[] R = { 
      "dL","e" 
    }; 

    String []L = { 

      "fL","eL","d" 
    }; 
    System.out.println(S[0]); 
    String random = (S[new Random().nextInt(S.length)]); 
    String chop = (S[new Random().nextInt(S.length)]); 

    System.out.println("S->"+random); 

如果時,從S進行隨機選擇,並獲得,例如「CR」後,我要替換,而不是「 R「從String [] R中進行一些隨機選擇,我應該怎麼做? 例如: 看我從S開始,然後我從S中得到隨機數,如果我得到了cR,我只用R字符串數組中的隨機數來替換R。 S-> CR-> CDL(而不是R I把分升)

+1

好的,首先要做的事情是:這個問題是關於Java的,所以標籤是這樣的。 – juanchopanza

+0

是的,抱歉,這是來自上一個問題。 – Nicholas

+0

問題是,當它的例如cR我不知道如何替換R。 – Nicholas

回答

1

我想這是你想要什麼:

import java.util.Random; 

public class gramatica { 
    public static void main(String[] args) { 

    String [] Vt = {"S","R","L"}; 
    String [] Vn = {"a","b","c","d","e","f"}; 

    String [] S = { 

      "aS","bS","cR","dL" 
    }; 

    String[] R = { 
      "dL","e" 
    }; 

    String []L = { 

      "fL","eL","d" 
    }; 
    //System.out.println(S[0]); 
    String rule = "S"; 

    Random r = new Random(); 

    // Make a loop 
    while(true) { 
     if(rule.contains("S")) { 
     rule = rule.replaceFirst("S", S[r.nextInt(S.length)]); 
     continue; 
     }; 
     if(rule.contains("R")) { 
     rule = rule.replaceFirst("R", R[r.nextInt(R.length)]); 
     continue; 
     }; 
     if(rule.contains("L")) { 
     rule = rule.replaceFirst("L", L[r.nextInt(L.length)]); 
     continue; 
     }; 

     // Nothing to change, break loop 
     break; 
    }; 

    // Now we got a random possible rule for S! :) 
    System.out.println("S->"+rule); 
    }; 
}; 

此代碼將產生你的語法隨機可能的字符串。 :)

+0

非常感謝你的hellp!這將是足夠的 – Nicholas

+0

所以,請點擊「接受答案」,所以我在這裏獲得一些聲譽。 = P – paulotorrens

+1

完成:3。再次感謝您 – Nicholas