编写一个程序来模拟抛硬币。首先,要求用户打电话"或者预测折腾。接下来,让用户知道你在掷硬币。然后报告用户是否正确。
示例:
Please call the coin toss (h or t): h Tossing... The coin came up heads. You win!
这是关于我应该做的事情。这是我到目前为止的代码:
package inClassCh4Sec8to9;
import java.util.Random;
import java.util.Scanner;
public class ClassCh4Sec8to9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter you guess (1 for heads, 0 for tails, 2 to quit):");
int call = input.nextInt();
int heads = 1;
int quit = 2;
int tails = 0;
if (call == quit) {
break;
} else if (call == heads) {
} else if (call == tails) {
} else {
System.out.println("invalid");
continue;
}
Random random = new Random();
int coinflip = random.nextInt(2);
if(call == coinflip){
System.out.println("Correct!");
}else{
System.out.println("Sorry, incorrect.");
}
}
}
}
我的问题:
答案 0 :(得分:1)
而不是Random.nextInt()
,我更喜欢nextBoolean()
。不要在循环中重新声明你的Random
。如果输入以h
开头,则guess
设置为true
;否则,请确保它有效(并将其设置为false
)。然后翻转coin
,并比较结果。像,
Scanner input = new Scanner(System.in);
Random random = new Random();
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine().toLowerCase();
boolean guess = call.startsWith("h"), coin = random.nextBoolean();
if (call.startsWith("q")) {
break;
} else if (!guess && !call.startsWith("t")) {
System.out.println("invalid");
continue;
}
if ((guess && coin) || (!guess && !coin)) {
System.out.printf("The coin came up %s. You win!%n", coin ? "heads" : "tails");
} else {
System.out.printf("The coin came up %s. You lose!%n", coin ? "heads" : "tails");
}
}
答案 1 :(得分:-1)
pd.date_range