Java – breaking nested for loops without using break

My project is finally finished, but my only problem is that my teacher doesn't accept the "interrupt" in our code Someone can help me solve this problem. I've been doing it for days. I don't seem to be able to make programs work without them The interrupt is in my dropyellowdisk and dropreddisk methods Apart from that problem, my connection to the four programs is perfect

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;
              }

    }}

Solution

From a programming point of view, this is just stupid (although I'm sure it has guiding advantages)

But in this particular case, there is a simple solution, because the loops you break are at the end of their respective methods Therefore, you can replace them with a return statement Namely:

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

  for (int i=6;i>=0;i--)
    {
      if (grid[i][c] == " ")
      {
        grid[i][c] = "Y";
        return; //break
      }}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>