Reputation: 79
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;
}
}}
Upvotes: 6
Views: 202
Reputation: 32670
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 break
ing 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
}}
}
Upvotes: 8
Reputation: 535
boolean flag = false;
for (int i=6;i>=0 && !flag;i--) {
if (grid[i][c] == " ") {
grid[i][c] = "Y";
flag = true;
}
}
Upvotes: 4
Reputation: 812
You can use boolean
flag instead of break with while
loop. Also you should compare strings by 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--;
}
}
Upvotes: 3