2013-10-02 75 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