我正在创建一个具有不同方法的骰子游戏。但是,我似乎无法弄清楚如何在我的方法之间传递变量以在其他方法中使用。它从一个菜单开始,用户可以在其中“选择”1(奇数)或 2(偶数),然后进入掷骰子方法以获取掷骰子的总和,然后使用计算方法来告诉用户他们是赢了还是输了。但是,我似乎无法弄清楚如何传递 diceSum 并在计算方法中使用的方法之间进行选择。
我似乎无法弄清楚如何在 diceCalc() 中使用 select 和 diceSum 来为用户打印答案。
private static void guess(){
Scanner input = new Scanner(System.in);
System.out.print("(1) Odd\n"
+"(2) Even\n"
+"(3) Quit Game\n"
+"What is your selection: ");
try {
int select = input.nextInt();
if(select == 1) {
System.out.println("");
diceRoll();
} else if(select == 2) {
System.out.println("");
diceRoll();
} else if(select == 3) {
System.out.println("Thank you for playing Dueling Dice v1.0...");
system.out(0);
}
private static void diceRoll() {
int roll1, roll2, diceSum;
roll1 = (int)(Math.random()*6+1);
roll2 = (int)(Math.random()*6+1);
diceSum = roll1 + roll2;
System.out.println(" Dice 1 roll = " + roll1);
System.out.println(" Dice 2 roll = " + roll2);
System.out.println("TOTAL dice roll = " + diceSum);
diceCalc(); // this is called in the main after the guess since guess performs the roll
}
private static void diceCalc() {
if (diceSum % 2 != 0 && select == 1 || diceSum % 2 == 0 && select == 2) {
if (select == 1) {
System.out.println("Dice rolled = " + diceSum + "and you selected odd");
} else {
System.out.println("Dice rolled = " + diceSum + "and you selected even");
}
System.out.println("CONGRATULATIONS! You WIN!!");
won++;
played++;
}else if (diceSum % 2 == 0 && select == 1 || diceSum % 2 != 0 && select == 2){
if (select == 1) {
System.out.println("Dice rolled = " + diceSum + "and you selected odd");
} else {
System.out.println("Dice rolled = " + diceSum + "and you selected even");
}
System.out.println("I am sorry you lost!");
lost++;
played++;
}
System.out.print("it is making it here!");
最佳答案
您可以将 diceSum 传递给 diceCalc 方法。
diceCalc(diceSum); // this is called in the main after the guess since guess performs the roll
然后将参数添加到diceCalc函数中。
private static void diceCalc(int diceSum)
关于java - 在方法之间传递变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44206587/