Reputation: 23
Is it possible to make nested loop based on user input in Java? For example, if the user inputs 3, then there are 3 loops that are nested (3 levels of loop). If it's possible, could you show me how?
I needed it to generate every possibilities of something. Every loop happens twice. So there are 2^n possibilities.
Thanks for the big help.
EDIT I haven't coded the looping calculation part yet because I'm still trying to figure out the algorithm. 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...
*/
}
}
is it enough? I changed the naming and mechanism a bit to make it shorter
Upvotes: 0
Views: 1222
Reputation: 825
You can't generate code at runtime, for this kind of problem simply go for recursion.
void fun(int n)
{
if(n==0)
return;
System.out.println(n);
fun(n-1);
}
Upvotes: 1