import java.util.Scanner;
import javax.swing.JOptionPane;
public class HW {
public static void main(String[] args){
while (retry == true){
getGuess();
getBet(balance);
checkGuess(getGuess());
updateBal(guessResult, betParsed);
goAgain(balance);
}
}
public static String getGuess(){
//Guess input
System.out.println("Guess: (H/T");
Scanner in = new Scanner(System.in);
boolean validInput = false;
String guess = null;
while (validInput == false){
guess = in.next();
if (guess.equals("H") || guess.equals("T")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + guess);
}
}
return guess;
}
public static boolean checkGuess(String sideGuess){
//Checks if the side is correct
double num = Math.round(Math.random());
boolean guessResult;
if (num == 0 && sideGuess.equals("H")){
System.out.println("Correct. The side was: H");
guessResult = true;
return true;
} else if (num == 1 && sideGuess.equals("T")){
System.out.println("Correct. The side was: T");
guessResult = true;
return true;
} else {
System.out.println("Incorrect.");
guessResult = false;
return false;
}
}
public static double getBet(double balance){
//Retrieves a bet from the user
Scanner in = new Scanner(System.in);
String betInput = null;
double betParsed = 0;
boolean validInput = false;
while (validInput == false){
betInput = in.next();
try {
betParsed = Double.parseDouble(betInput);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invlaid Input: " + betInput);
}
if (betParsed > balance || betParsed < 0){
JOptionPane.showMessageDialog(null, "Invalid Input! You have: $" + balance);
} else {
validInput = true;
}
}
return betParsed;
}
public static double updateBal(boolean checkGuess, double getBet){
//Updates the balance based on the bet
double balance = 0;
if (checkGuess == true){
balance = balance + getBet * 2;
System.out.println("Your balance is now: $" + balance);
} else {
System.out.println("Your balance is now: $" + balance);
balance = balance - getBet;
}
return balance;
}
public static boolean goAgain(double balance){
//Determines if new play is needed
Scanner in = new Scanner(System.in);
boolean validInput = false;
String goAgainInput = null;
boolean retry;
while (validInput == false){
System.out.println("Go again? (Y/N)");
goAgainInput = in.next();
if (goAgainInput.equals("Y") || goAgainInput.equals("N")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + goAgainInput);
}
}
if (goAgainInput.equals("Y")){
retry = true;
return true;
} else {
System.out.println("You ended with: $" + balance);
retry = false;
return false;
}
}
}
编辑了代码。
我试图将一些定义的变量传递给一些方法,但似乎我不能使用它们?
我怎样才能解决这个问题?
似乎它们不是“本地的”,我无法理解,因为它们是在方法中定义的。我一定是在想。