我有一個Java任務,無法讓它工作。Java的猜測遊戲
我正在做1-100之間的猜謎遊戲。當我運行我的代碼時,它一直告訴我「太低」,無論是正確還是過高。
這裏是我的代碼:
public static void main(String[] args) throws java.io.IOException {
int i, ignore, answer = 64;
do {
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("Can you guess it?");
i = (int) System.in.read();
do {
ignore = (int) System.in.read();
} while (ignore != '\n');
if (i == answer) System.out.println("**RIGHT**");
else {
System.out.print("...Sorry, you're ");
if (i < answer)
System.out.println("too low");
else
System.out.println("too high");
System.out.println("Try again!\n");
}
} while(answer != i);
}
由於與調用'System.in.read()',你得到一個'char'。你應該構建一個'Scanner',並將其稱爲'nextInt()'方法,如下所示:'掃描儀掃描=新掃描儀(System.in); i = scan.nextInt();' – Majora320
'System.in.read()'需要下一個**字節**而不是下一個** int **。有一個很大的區別 –
你應該使用調試器,甚至只是打印變量,看看你的代碼實際上做什麼,然後再問你沒有任何測試。如果你這樣做,把它們寫入問題。 – Nier