基于Java中用户输入的嵌套循环

时间:2016-12-06 09:52:48

标签: java loops nested-loops

是否可以根据Java中的用户输入进行嵌套循环?例如,如果用户输入3,则有3个嵌套循环(3个循环级别)。如果有可能,你能告诉我怎么做吗?

我需要它来产生某种东西的可能性。每个循环发生两次。所以有2 ^ n种可能性。

感谢您的大力帮助。

修改 我还没有对循环计算部分进行编码,因为我还在试图找出算法。 的 Kriteria.java

public class Kriteria {

    String name;
    int min, max;
    double lowMembership, highMembership;
public Kriteria(String name, int min, int max,low,high) {
        this.name = name;
        this.min = min;
        this.max = max;
        this.lowMembership = low;
        this.highMembership = high;
    }

}

MainClass.java

public class MainClass {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    ArrayList<Kriteria> listKriteria = new ArrayList();

//later on the user can decide how many kriteria he wanted and create them            
    Kriteria kriteria1,kriteria2,kriteria3;

    kriteria1 = new Kriteria("Kriteria 1", 1, 10, 4,3,5);
    listKriteria.add(kriteria1);
    kriteria2= new Kriteria2("Kriteria 2", 5, 20, 13,7,18);
    listKriteria.add(kriteria2);
    kriteria3 = new Kriteria3("Kriteria 3", 3, 8, 5,4,7);
    listKriteria.add(kriteria3);

/* I want something like this:

1st 
double result= Kriteria1.lowMembership + Kriteria2.lowMembership + Kriteria3.lowMembership;
2nd
double result= Kriteria1.lowMembership + Kriteria2.lowMembership + Kriteria3.highMembership;
3rd
double result= Kriteria1.lowMembership + Kriteria2.highMembership + Kriteria3.highMembership;
and so on for each possibility...
*/

   }        
}

够了吗?我稍微更改了命名和机制以缩短

1 个答案:

答案 0 :(得分:1)

你不能在运行时生成代码,因为这种问题只是去递归。

void fun(int n)
{
     if(n==0)
         return;
     System.out.println(n);
     fun(n-1);
}