连续三个头 Java 程序?
Three Heads in a row Java Program?
在JAVA中编写一个程序,模拟抛硬币并输出连续出现三个“正面”所需的抛硬币次数。该程序还将模拟抛掷的“正面”和“反面”输出到屏幕。例如,您的程序可能会产生如下输出:
- 示例 1:HTHHH
- 5
- 示例 2:TTTHTHHTTPTTTHHH
- 14
现在当我 运行 它时,它连续打印 H 并且 运行s 无限次。它也没有翻转尾巴,只有头部。那么有人可以帮我修复我的代码吗......谢谢。
我的代码:
import java.util.*;
public class threeHeads {
public static void main(String[] args) {
boolean first = false;
boolean second = false;
int count = 0;
Random random = new Random();
while(true){
int n = random.nextInt(2) + 1; //1 is Heads, 2 is Tails
if (n == 1){
System.out.println("H");
count++;
if (first == false){
first = true;
} else if (second == false){
second = true;
} else if (second == true){
break;
}
}
else {
System.out.println("T");
first = false;
second = false;
count++;
}
}
if (count == 3){
System.out.println(count);
}
}
}
尝试一下这段代码,看看它是否能达到你想要的效果
public class flipper {
public static void main(String[] args) {
int heads = 0;
int count = 0;
while (heads < 3) {
int flip = (int)(Math.random() * 2); // range [0, 1]
count++;
if (flip == 0) {
System.out.print("H");
heads++;
} else {
System.out.print("T");
heads = 0;
}
}
System.out.println("\nIt took " + count + " flips to achieve three heads in a row");
}
}
在JAVA中编写一个程序,模拟抛硬币并输出连续出现三个“正面”所需的抛硬币次数。该程序还将模拟抛掷的“正面”和“反面”输出到屏幕。例如,您的程序可能会产生如下输出:
- 示例 1:HTHHH
- 5
- 示例 2:TTTHTHHTTPTTTHHH
- 14
现在当我 运行 它时,它连续打印 H 并且 运行s 无限次。它也没有翻转尾巴,只有头部。那么有人可以帮我修复我的代码吗......谢谢。
我的代码:
import java.util.*;
public class threeHeads {
public static void main(String[] args) {
boolean first = false;
boolean second = false;
int count = 0;
Random random = new Random();
while(true){
int n = random.nextInt(2) + 1; //1 is Heads, 2 is Tails
if (n == 1){
System.out.println("H");
count++;
if (first == false){
first = true;
} else if (second == false){
second = true;
} else if (second == true){
break;
}
}
else {
System.out.println("T");
first = false;
second = false;
count++;
}
}
if (count == 3){
System.out.println(count);
}
}
}
尝试一下这段代码,看看它是否能达到你想要的效果
public class flipper {
public static void main(String[] args) {
int heads = 0;
int count = 0;
while (heads < 3) {
int flip = (int)(Math.random() * 2); // range [0, 1]
count++;
if (flip == 0) {
System.out.print("H");
heads++;
} else {
System.out.print("T");
heads = 0;
}
}
System.out.println("\nIt took " + count + " flips to achieve three heads in a row");
}
}