Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of a nested for loop without using break

My project is finally complete, but my only problem is that my teacher does not accept "breaks" in our code. Can someone help me resolve this issue, I have been working on it for days and I just can't seem to get the program to work without using them. The breaks are located in my DropYellowDisk and DropRedDisk methods. Other then that issue, my connect four program is flawless.

    private static void DropYellowDisk(String[][] grid) {

        int number = 0;
         Scanner keyboard = new Scanner (System.in);
         System.out.println("Drop a yellow disk at column (1–7): ");
         int c = 2*keyboard.nextInt()+1;


         for (int i=6;i>=0;i--)
            {
              if (grid[i][c] == " ")
              {
                grid[i][c] = "Y";
                break;
              }}
    }

    private static void DropRedDisk(String[][] grid) {

         Scanner keyboard = new Scanner (System.in);
         System.out.print("Drop a red disk at column (1–7): ");
         int c = 2*keyboard.nextInt()+1;
         for (int i =6;i>=0;i--)
            {
              if (grid[i][c] == " ")
              {
                grid[i][c] = "R";
                break;
              }

    }}
like image 447
Alex Avatar asked Nov 24 '14 21:11

Alex


1 Answers

my teacher does not accept "breaks"

From a programming standpoint, that's just plain silly (although I'm sure it has merit from an instructional one).

But there's an easy workaround in this particular case because the loops your breaking from are all at the end of their respective methods. As such, you can replace them with return statements. i.e:

private static void DropYellowDisk(String[][] grid) {

  for (int i=6;i>=0;i--)
    {
      if (grid[i][c] == " ")
      {
        grid[i][c] = "Y";
        return; //break
      }}
}
like image 130
drew moore Avatar answered Sep 18 '22 19:09

drew moore