我正在嘗試制作這個簡單的賠率和偶數(shù)游戲。該程序可以完美運行,直到“1”。問題是:它不是將“手指”和“計算機”相乘,而是直接給出“計算機”的值,雖然我沒有從其余代碼中得到任何錯誤,但我也沒有得到任何輸出。我將“name”、“oe”和“finger”設(shè)為靜態(tài)以便能夠在循環(huán)外使用它們。import java.util.Scanner;import java.util.Random;public class OddsAndEvens {static String name; static String oe;static int finger;public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Let’s play a game called “Odds and Evens”"); System.out.println("What is your name?"); String name = input.next(); while (true) { System.out.println("Hello " + name + " which one do you choose? (O)dds or (E)vens?"); String oe = input.next(); if (oe.equalsIgnoreCase("e")) { System.out.println(name + " has picked evens! The computer will be odds."); break; } if (oe.equalsIgnoreCase("o")) { System.out.println(name + " has picked odds! The computer will be evens."); break; } else { System.out.println("You have typed an invalid answer, lets try again"); } } while (true) { System.out.print("How many \"fingers\" do you put out? "); int finger = input.nextInt(); if (finger >= 0 && finger <= 5) { break; } else { System.out.println("Please write a number between 0 and 5"); } } Random rand = new Random(); int computer = rand.nextInt(5) + 0; System.out.println("Computer plays number " + computer); System.out.println("----------------------------------------------"); int sum = finger + computer; //1<------------------------------ if (sum % 2 == 0) { System.out.println(sum + " is even!"); if (oe.equalsIgnoreCase("e") && (sum % 2 == 0)) { System.out.println(name + " wins!"); } else { System.out.println("Computer wins!"); } } } }}}
3 回答

揚帆大魚
TA貢獻(xiàn)1799條經(jīng)驗 獲得超9個贊
在第二個 while 循環(huán)中,您初始化一個finger
僅在 while 循環(huán)內(nèi)有效的新局部變量,方法是說int finger =
而不是說來調(diào)用全局靜態(tài)變量finger finger =
。
結(jié)果,全局變量finger
沒有被初始化,sum
也沒有什么可以添加到變量中computer
。
添加回答
舉報
0/150
提交
取消