あなたは月の日付を入力すると、あなたが生まれて、Enterキーを押しますされている、すなわち
System.out.print("On what day of the month were you born? ");
int monInt = scan.nextInt();
あなたは彼らが番号を入力することが期待されています。 13を入力してEnterを押すと、enterを押したので、13\n
と入力したことがコンピュータに表示されます。 nextInt()への呼び出しは13
となりますが、\n
のままにしてください。 nextLine()が動作する方法は、\n
の次の出現まで読み取ることです。つまり、\n
が行を終了するために使用されます。この問題は、次に System.out.print("During what year were you born? "); int year = scan.nextInt();
と呼んでいますが、まだ生まれた月の文字列表記を入力することを期待しています。したがって、Stringを入力すると、nextInt()の呼び出しは整数ではないため、整数として解析できません。これはStringです。 これを修正するには2つの方法があります。入力バッファから\n
を取り除くために初めてnextInt()を呼び出した直後にscan.nextLine()を呼び出すか、またはscanを使うことができます。 scan.nextLine()の代わりにnext()を呼び出して、その月のString表現を格納します。 next()は(通常)次のスペースまで読み込まれるので、入力バッファにまだ存在する\n
は問題を起こさないでしょう。あなたのコードの機能バージョン、次のことになる -
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("On what day of the month were you born? ");
int monInt = input.nextInt();
System.out.print("What is the name of the month in which you were born? ");
String monStr = input.next();
System.out.print("During what year were you born? ");
int year = input.nextInt();
input.close();
System.out.println("You were born on " + monStr + ", " + monInt + year
+ ". You're mighty old!");
}
と、このプログラムからの出力例は、あなたがまだ出力にそれを得るために書式設定テキストを変更する必要が
On what day of the month were you born? 13
What is the name of the month in which you were born? October
During what year were you born? 1943
You were born on October, 131943. You're mighty old!
注だろうあなたが望むのとまったく同じですが、あなたが以前に抱えていた問題は修正されています。
int monInt = input.nextInt(); // Reads 8
System.out.print("What is the name of the month in which you were born? ");
String monStr = input.nextLine(); // Reads to end of line, aka '\n'
System.out.print("During what year were you born? ");
int year = input.nextInt(); // reads next token as int, which is "May"
と
[読み取り文字列next()とnextLine()Java]の複製が可能です(http://stackoverflow.com/questions/8873351/reading-strings-next-and-nextline-java) – Dukeling
の代わりに 'next'を使用してください月を読むための 'nextLine' – Dukeling
エラーをコードとしてフォーマットしてください。これは混乱のように見えます。 –