我正在從Y. Daniel Liang着的「Java編程入門」一書中進行練習。在這個程序中,用戶在一個月內被呈現爲具有各種日期的表格。如果用戶的生日在所呈現的表格中,則用戶提示'是'而不是'N'。根據用戶提示'Y'的次數,程序應該猜測用戶的生日是哪一天。當我運行程序時,顯示第一組日期,我輸入'Y'或'N'。然後打印set2和3,但我不會輸入任何輸入。當打印設置4時,我可以再次鍵入輸入,但是在打印設置5之後,不能輸入任何輸入。爲什麼我只能在set1和4之後輸入輸入內容?代碼顯示如下:Java中的生日猜測遊戲,代碼行被無緣無故地跳過
import java.util.Scanner;
public class GuessBirthday {
public static void main(String[] args)
throws java.io.IOException {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
" 17 19 21 23\n" +
" 25 27 29 31";
String set2 =
" 2 3 6 7\n" +
" 10 11 14 15\n" +
" 18 19 22 23\n" +
" 26 27 30 31";
String set3 =
" 4 5 6 7\n" +
" 12 13 14 15\n" +
" 20 21 22 23\n" +
" 28 29 30 31";
String set4 =
" 8 9 10 11\n" +
" 12 13 14 15\n" +
" 24 25 26 27\n" +
" 28 29 30 31";
String set5 =
" 16 17 18 19\n" +
" 20 21 22 23\n" +
" 24 25 26 27\n" +
" 28 29 30 31";
int day = 0;
// Create a scanner
Scanner input = new Scanner(System.in);
// Prompt the user to answer questions
System.out.print("Is your birthday in set1?\n");
System.out.print(set1);
System.out.print("\nEnter (Y) for yes or (N) for no: ");
char answer = (char) System.in.read();
if (answer == 'Y')
day += 1;
System.out.print("\nIs your birthday in set2?\n");
System.out.print(set2);
System.out.print("\nEnter (Y) for yes or (N) for no: ");
answer = (char) System.in.read();
if (answer == 'Y')
day += 2;
System.out.print("\nIs your birthday in set3?\n");
System.out.print(set3);
System.out.print("\nEnter (Y) for yes or (N) for no: ");
answer = (char) System.in.read();
if (answer == 'Y')
day += 4;
System.out.print("\nIs your birthday in set4?\n");
System.out.print(set4);
System.out.print("\nEnter (Y) for yes or (N) for no: ");
answer = (char) System.in.read();
if (answer == 'Y')
day += 8;
System.out.print("\nIs your birthday in set5?\n");
System.out.print(set5);
System.out.print("\nEnter (Y) for yes or (N) for no: ");
answer = (char) System.in.read();
if (answer == 'Y')
day += 16;
System.out.println("\nYour birthday is " + day + "!");
}
}
爲什麼如果你不使用'Scanner input'? – Pshemo
練習是重寫程序,其中整數0和1用於「否」和「是」,取而代之的是將字符「Y」和「N」作爲輸入。我實際上忘記了當使用System.in.read()時我不需要它。 。但你提出一個有效的觀點,並感謝您指出了這一點! – Esben86