我刚开始使用比主要方法更复杂的方法进行编码。我被分配用三个硬币进行比赛。哪个硬币按顺序先翻转 2 个正面和 2 个反面为赢。我编写了一个 if else 语句来确定哪个硬币获胜,但没有一个 if 语句被执行。如果您在我的 if else 语句或其他地方看到错误,请告诉我。我还必须包含其他方法的其他代码程序。
public class FlipRace
{
public static void main (String[] args)
{
final int GOALHEAD = 2;
final int GOALTAIL = 2;
int count1 = 0, count2 = 0, count3 = 0, count10 = 0, count20 = 0, count30 = 0;
// Create three separate coin objects
Coin coin1 = new Coin();
Coin coin2 = new Coin();
Coin coin3 = new Coin();
while (count1 <= GOALHEAD && count10 <= GOALTAIL || count2 <= GOALHEAD && count20 <= GOALTAIL || count3 <= GOALHEAD && count30 <= GOALTAIL)
{
coin1.flip();
coin2.flip();
coin3.flip();
// Print the flip results (uses Coin's toString method)
System.out.print ("Coin 1: " + coin1);
System.out.println (" Coin 2: " + coin2);
System.out.println (" Coin 3: " + coin3);
// Increment or reset the counters
if (coin1.isHeads())
count1++;
else
count10++;
if (coin2.isHeads())
count2++;
else
count20++;
if (coin3.isHeads())
count3++;
else
count30++;
}
// Determine the winner
if (count1 == GOALHEAD && count10 == GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 == GOALHEAD && count20 == GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 == GOALHEAD && count30 == GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
}
}
这是我的输出:
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Heads
Coin 3: Heads
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
It's a TIE!// this message comes up every time because something is wrong