我對 java 和一般的編碼很陌生,我想弄清楚如何讓這個游戲為學校的一個專案作業。它是為了讓您輸入一個月,然后它會要求您選擇一天,但是當我輸入一個月時,它總是說它是無效的輸入,這就是我希望它在無效時執行的操作月。我究竟做錯了什么?
import java.util.*;
class Main {
public static void main(String[] args) {
boolean game = true;
do {
System.out.println("Welcome to the Famous Date game!");
System.out.println("Please choose a month");
Scanner Month = new Scanner(System.in);
String Choice = Month.nextLine();
String[] Months = {"January", "February", "March", "April", "May", "June","July",
"August","September","October","November", "December"};
List<String> mylist = Arrays.asList(Months);
if (Choice.equals(mylist)) {
System.out.println("Please choose a day");
}
else
System.out.println("That is not a valid month");
}
while (game=true);
}
}
uj5u.com熱心網友回復:
嘗試測驗是否包含list.contains()
其他方法中的月份和日期,只需呼叫它
uj5u.com熱心網友回復:
使用 if (mylist.contains(Choice)) 有效!太感謝了
uj5u.com熱心網友回復:
如果您被允許使用java.time包中的類,那么您可以使用Month(它是一個enum)。這使您不必創建自己的串列。
另外,用戶選擇一個月后,還需要選擇一天。我假設用戶應該輸入一個有效的日期,例如當輸入的月份是二月時輸入數字 30 將構成無效的日期。要檢查輸入的日期是否有效,您可以使用YearMonth類,該類具有回傳每個月的天數并考慮閏年的方法。請參閱此 SO 問題:特定年份特定月份的天數?
這是一個SSCCE
(代碼后的注釋。)
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.temporal.ChronoField;
import java.util.InputMismatchException;
import java.util.Scanner;
public class GameMain {
public static void main(String[] args) {
int year = LocalDate.now().get(ChronoField.YEAR);
Scanner keyboard = new Scanner(System.in);
boolean game = true;
do {
System.out.print("Please choose a month: ");
String month = keyboard.nextLine();
try {
Month theMonth = Month.valueOf(month.toUpperCase());
YearMonth daysInMonth = YearMonth.of(year, theMonth);
do {
System.out.print("Please choose a day: ");
try {
String val = keyboard.nextLine();
int day = Integer.parseInt(val);
if (day < 0 || day > daysInMonth.lengthOfMonth()) {
System.out.printf("%s does not have %d days.%n", theMonth, day);
}
else {
game = false;
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Please enter a number.");
}
} while (game);
}
catch (IllegalArgumentException xIllegalArgument) {
System.out.println("That is not a valid month");
}
} while (game);
}
}
請注意,您只需要創建Scanner一次。在您問題的代碼中,您正在回圈Scanner的每次迭代中創建一個do-while。
Also, if you enter a value that does not exist in an enum, an IllegalArgumentException is thrown.
And method parseInt throws NumberFormatException if the entered value is not an integer.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440657.html
標籤:爪哇 数组 细绳 java.util.scanner
