import java.util.Scanner;
import javax.swing.JOptionPane;
public class Coin {
public static void main(String[] args)
{
boolean validFinalInput = false;
boolean validBetInput = false;
boolean validGuessInput = false; //Determines if the guess is a valid input
boolean validBet = false; //Determines if the bet is valid
boolean goAgain = true;
double num; //Unparsed Side Determiner
double balance = 100;
String Bet = null; //Bet Input
double bet = 0; //Parsed Bet
String Guess = null; //H or T
String Side = null; //Determines Side
String GoAgain = null; //Y/N Retry input
Scanner in = new Scanner(System.in);
while (goAgain == true){ //While true, the player will keep playing.
num = Math.round(Math.random()); //Declares Number
if (num == 1){
Side = "H";
} else if (num == 0){
Side = "T";
}
while (validGuessInput == false){ //Determines if the input is valid
System.out.println("Guess: (H/T)");
Guess = in.next();
if (Guess.equals("H") || Guess.equals("T")){
validGuessInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Guess!");
validGuessInput = false;
}
}
while (validBet == false){
while (validBetInput == false){
try {
System.out.println("Bet? (Your balance is $" + balance);
Bet = in.next();
bet = Double.parseDouble(Bet);
if (bet > 0){
validBetInput = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Bet!");
}
}
if (bet <= balance && bet >= 0){
validBet = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Bet!");
validBet = false;
}
}
if (Guess.equals(Side)){
balance = balance + (bet * 2);
System.out.println("Correct! The side was: " + Side);
System.out.println("Your balance is now: $" + balance);
} else {
balance = balance - bet;
System.out.println("Incorrect! The side was: " + Side);
System.out.println("Your balance is now: $" + balance);
}
if (balance == 0){
System.out.println("You ran out of money. Ending Game.");
break;
}
System.out.println("Go again? (Y/N)");
GoAgain = in.next();
while (validFinalInput == false);
System.out.println("Go again? (Y/N)");
GoAgain = in.next();
validGuessInput = false;
validBet = false;
validBetInput = false;
if (GoAgain.equals("Y")){
goAgain = true;
validFinalInput = true;
} else if (GoAgain.equals("N")){
goAgain = false;
validFinalInput = true;
System.out.println("Thanks for playing! You ended with: $" + balance);
} else {
System.out.println("Invalid Input!");
}
}
}
}
所以我寫了這個代碼爲「頭或尾巴」風格的遊戲。它最初的工作,但後來我決定添加一些功能,它破壞。基本上,它到了最後,但卡在最後一個輸入(Y/N)上。頭或尾巴游戲 - 循環問題
有人能告訴我我做錯了什麼嗎?
對缺乏評論感到抱歉。
我也意識到我的變量並不完全遵循約定,所以也很抱歉。
謝謝。
你已經粘貼了太多的代碼。將其解析爲僅與您的實際問題相關的代碼。此外,還有一個原因存在命名約定。名爲'goAgain'的布爾值和名爲'GoAgain'的String使您的代碼非常混亂。 – nhgrif
*我也意識到我的變量並不完全遵循約定,所以也爲此感到抱歉。*:那麼爲什麼在提問之前不修復它?現在好於以後。它會使你的代碼對所有讀者更具可讀性。你有沒有試過用調試器執行代碼?這是你應該學習的東西。 –
未來代碼的提示,當代碼獲得這麼長時間時,最好將其拆分爲方法。如果你像我一樣淺,更容易閱讀,更容易調試,看起來更漂亮。 – arynaq