0

これまでのところコードは機能していますが、2 つの問題があります。このコードでは、月、日、年を入力すると、何日あるかがわかります。基本的にはうるう年のチェッカーですが、毎月含まれています(何らかの理由で)。

現在、ケースを機能させる唯一の方法は数字を使用することですが、ユーザーが実際の月の名前を入力として入力できるようにしたいと考えています。ケースの月名に名前を付けようとすると、変数を認識しないと表示されます。それが私の最初の問題です。

私の 2 番目の問題は、ユーザーが整数ではない文字を「年」セクションに入力しようとした場合に、エラー メッセージを表示することです。誰かが私に .hasNextInt() を使用するように言いましたが、その機能や実装方法がまったくわかりません。ここで他の人のコードを見て、それがどのように使用されていないかを理解しようとしました。これが私のコードです。提案やガイダンスをいただければ幸いです。前もって感謝します!

public class MonthLength {
  public static void main(String[] args) {
    // Prompt the user to enter a month
    SimpleIO.prompt("Enter a month name: ");
    String userInput = SimpleIO.readLine();
    int month = Integer.parseInt(userInput);

    // Terminate program if month is not a proper month name
    if (month < 1 || month > 12) {
      System.out.println("Illegal month name; try again");
      return;
    }

    // Prompt the user to enter a year
    SimpleIO.prompt("Enter a year: ");
    userInput = SimpleIO.readLine();
    int year = Integer.parseInt(userInput);

    //Terminate program if year is not an integer
    if (year < 0) {
       System.out.println("Year cannot be negative; try again");
       return;
    }

    // Determine the number of days in the month
    int numberOfDays;
    switch (month) {
      case 2:  // February
               numberOfDays = 28;
               if (year % 4 == 0) {
                 numberOfDays = 29;
                 if (year % 100 == 0 && year % 400 != 0)
                   numberOfDays = 28;
               }
               break;

      case 4:  // April
      case 6:  // June
      case 9:  // September
      case 11: // November
               numberOfDays = 30;
               break;

      default: numberOfDays = 31;
               break;
    }

    // Display the number of days in the month
    System.out.println("There are " + numberOfDays +
                       " days in this month");
  }
}
4

3 に答える 3

0

以前の Java 7バージョンでは、 Stringをswitchの引数として使用できません。Java 7 では、スイッチの引数として文字列を渡すことができます。

ここで Enum を使用できます。

enum Months{
JAN,FEB,MAR,APR}
于 2012-11-02T21:37:06.017 に答える
0
  1. 最初の問題についてenum は、Java 6 列挙型の値 () はどのように実装されていますか?を使用できます。

  2. String2 番目の問題については、ユーザーに a を入力し、それを使用Integer.parseInt(String)して変換するように求めることができるintため、チェックを実行する必要はありません。それが役立つことを願っています

于 2012-11-02T21:40:20.070 に答える
0

Chaitanya10 は、あなたの創刊号がなぜそうなのかを詳しく説明しています。文字列 (以前の Java バージョン) で比較を行う必要がある場合は、if-else ブロックを作成する必要があります。

if (monthInput.toLower().equals("january") {
  month = 1;
} else if (monthInput.toLower().equals("february") {
  ....etc....
}

2番目の問題については、ユーザー入力を としてキャプチャしString、チェックを使用して、入力した数値であることを確認します。次のような関数を作成します。

public boolean isNumeric(String input) {
  try {
    Integer.parseInt(input);
    return true;
  } catch (NumberFormatException numForEx) {
    return false;
  }
}

それが true を返す場合、文字列を安全に整数に変換できます。

year = Integer.parseInt( input );
于 2012-11-02T21:42:46.347 に答える