I am making a snakes and ladders game on console. I'm trying to make it so that the ladderBottoms is always less than the ladderTops. However I keep running into errors. The code I have been trying is a recursive method for it to redo the method until it is correct...

public static void ladders() {
  for (int i = 0 ; i < 6 ; i++){
   ladderBottoms [i] = (int) ((Math.random () * 80)+1);
   ladderTops [i] = (int) ((Math.random () * 80)+1);`
      if(ladderBottom[i] > ladderTop[i])
       ladders();
  }//for
}//ladders
有帮助吗?

解决方案

This code is not good. You are attempting, on each recursion to regenerate the entire array from scratch! In fact the probability of your successfully generating the ladders is about 1 / 64.

If I were you, I'd drop the recursion and adjust the loop:

public static void ladders() {
  for (int i = 0 ; i < 6 ; ){    
   ladderBottoms [i] = (int) ((Math.random () * 80)+1);
   ladderTops [i] = (int) ((Math.random () * 80)+1);
      if(ladderBottom[i] <= /*do you really want =*/ ladderTop[i]){
           i++; /* this is OK so increment; else have another go*/
      }
  }//for
}//ladders

An empty expression in a for loop is perfectly legal in Java.

Do take note of my comment in the code. Do you really want a unit-length ladder? If not then replace the <= in the conditional with <.

As a rule of thumb, always try to avoid recursive functions: they can be difficult to follow in a 3am debugging session and also, particularly with ramdomisation, can, once in a while, cause a stack to overflow.

其他提示

Don't recursive the total method just retry randoms another time.

public static void ladders()
{
    for (int i = 0 ; i < 6 ; i++)
    {
        do{
            ladderBottoms [i] = (int) ((Math.random () * 80)+1);
            ladderTops [i] = (int) ((Math.random () * 80)+1);
        }while(ladderBottom[i] >= ladderTop[i]);
    }//for
}//ladders

Not tested.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top