gpt4 book ai didi

java - 有没有一种方法可以确保 while 循环在请求输入之前不会运行一次?

转载 作者:行者123 更新时间:2023-12-02 09:04:11 25 4
gpt4 key购买 nike

我正在编写一个抛硬币程序。基本上,用户会被询问他们想玩多少游戏。然后,while 循环运行游戏,要求用户输入由空格分隔的几次抛硬币(正面或反面,例如 H H H T H)。然后程序将用户输入字符串转换为数组,for 循环遍历数组并检查 head(大写 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() 没有捕获用于输入游戏数量的换行符,因此您可以添加 scanner.nextLine();之后防止游戏立即结束。

第二个问题是 for 循环中的条件。删除 -1 以循环遍历数组中的所有元素。

第三个问题是,在计算分数时,您将一个整数除以一个始终大于或等于该整数的数字,因此小数被截断或结果为 1。您可以转换整数在运算中加倍或将 heads 声明为 double,或者如果您不关心百分比结果的小数位,则可以在除法之前乘以 100。

import java.util.Scanner;
public class Main {
public static void main (String []args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many games? ");
int games = scanner.nextInt();
System.out.println("Games: "+ games);
scanner.nextLine();
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; i++){
System.out.println("Input["+ i +"]: "+ inputArray[i]);
if (inputArray[i].equals("H")){
heads++;
System.out.println("Heads count: "+ heads);
}

}//exit for loop

double score = ((double)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++;
}
}
}

关于java - 有没有一种方法可以确保 while 循环在请求输入之前不会运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com