Break out of a nested loop without using a break

My project is finally completed, but my only problem is that my teacher does not accept β€œbreaks” in our code. Can someone help me solve this problem, I worked on it for several days, and I just can not get the program to work without using them. Breaks are in my DropYellowDisk and DropRedDisk methods. Another, then this problem, my four connection 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; } }} 
+6
source share
3 answers

my teacher doesn't take "breaks"

From a programming point of view, this is just plain stupid (although I'm sure it has the advantage of learning).

But in this particular case there is an easy way, because the loops of your break ing are all at the end of their respective methods. So you can replace them with return . ie:

 private static void DropYellowDisk(String[][] grid) { for (int i=6;i>=0;i--) { if (grid[i][c] == " ") { grid[i][c] = "Y"; return; //break }} } 
+8
source
 boolean flag = false; for (int i=6;i>=0 && !flag;i--) { if (grid[i][c] == " ") { grid[i][c] = "Y"; flag = true; } } 
+4
source

You can use the boolean flag instead of breaking with a while . You should also compare strings using the equals method.

 private static void DropYellowDisk(String[][] grid) { int number = 0; boolean flag=true; Scanner keyboard = new Scanner (System.in); System.out.println("Drop a yellow disk at column (1–7): "); int c = 2*keyboard.nextInt()+1; int i=6; while(i>=0&& flag) { if(grid[i][c].equals(" ")) { grid[i][c]="Y"; flag=false; } i--; } } 
+3
source

Source: https://habr.com/ru/post/978645/


All Articles