【发布时间】:2020-01-29 03:42:33
【问题描述】:
我正在编写一个抛硬币程序。基本上,询问用户他们想玩多少游戏。然后,while 循环运行游戏,要求用户输入几个由空格分隔的掷硬币(正面或反面,例如 H H H T H)。然后程序将用户输入的字符串转换为一个数组,for循环遍历数组并检查heads(大写H)并将其存储在heads变量中。分数的计算方法是将数组中的正面数除以数组的长度,然后将其乘以 100 得到一个百分比。如果得分为 50% 或以上,则玩家获胜。如果低于 50%,玩家就输了。我发现的两个错误是,在我输入任何输入之前,while 循环已经运行了一次。此外,分数似乎计算不正确,它总是返回 0.0% 或 100.0%。我认为它与 inputArray.length 有关,但我不能说。谢谢。
import java.util.Scanner;
public class HeadTailGenerator {
public static void main (String []args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many games?");
int games = scanner.nextInt();
int count = 0;
int heads =0;
while (count<games){
System.out.print("Enter your flips for game "+ count+": ");
String input = scanner.nextLine();
String [] inputArray = input.split("\\s+");
for (int i = 0; i <inputArray.length-1; i++){
if (inputArray[i].equals("H")){
heads++;
}
}//exit for loop
double score = (heads/(inputArray.length)*100);
if (score >= 50.0){
System.out.println("Game "+ count + ": "+ heads + " heads ("+ score+ "%); You win!");
}
else {
System.out.println("Game "+ count + ": "+ heads + " heads ("+ score+ "%); You lose!");
}
count++;
}
}
}
【问题讨论】:
-
看看这个,可能和
nextInt()有同样的问题; stackoverflow.com/questions/23450524/… -
另外,请打印inputArray的内容,查看拆分后有哪些值。
标签: java arrays while-loop