[英]Is there a way to ensure a while loop does not run one time before asking for input?
我正在編寫一個拋硬幣程序。 基本上,用戶會被問到他們想玩多少游戲。 然后,while 循環運行游戲,要求用戶輸入幾個由空格分隔的擲硬幣(正面或反面,例如 HHHTH)。 然后程序將用戶輸入字符串轉換為數組,for 循環遍歷數組並檢查頭(大寫 H)並將其存儲在頭變量中。 分數的計算方法是將數組中的正面數除以數組的長度並將其乘以 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
為雙或者你也可以乘划分,如果你不關心%的結果小數前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++;
}
}
}
不久前我遇到了這個。 第一個問題,為什么 while 循環在接受用戶輸入之前運行一次是因為掃描器處理讀取nextInt()
。 Scanner 剛剛讀取了它到達的下一個整數值,但還沒有到達行尾。 因此,當您在 while 循環中調用scanner.nextLine()
時,它實際上只是讀取第一行輸入的末尾,這就是為什么您在那里得到零的原因。
第二個問題,總是為零,與您使用的數據類型有關。 請記住,int / int = int。 所以,當你除以 3/4 = 0 時,因為 int 被截斷了。 您存儲在雙精度數中無關緊要,是整數除法出錯了。 如果您只是將頭部更改為浮動,它將糾正該問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.