UPDATE! 元の問題を修正しましたが、若いメンバーと古いメンバーを表示する際にエラーが発生し、次のエラーがスローされます。助言がありますか?スレッドのおかげで「完了」と入力すると、Java終了配列
例外 "メイン" java.lang.IndexOutOfBoundsException:インデックス:4、サイズ:4 java.util.ArrayList.rangeCheck(ArrayList.java:653)で java.util.ArrayList.getで( ArrayList.java:429)NameAge.mainで (NameAge.java:46)
import java.util.Scanner;
import java.util.ArrayList;
public class NameAge {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX_VALUE = 4;
ArrayList<String> nameList = new ArrayList<String>();
ArrayList<Integer> ageList = new ArrayList<Integer>();
Integer[] ages = new Integer[10];
for (int i = 0; i < MAX_VALUE; i++) {
System.out.print("Enter a name: ");
String currentLine = input.next();
if (currentLine.equals("DONE")) {
break;
}
nameList.add(currentLine);
System.out.print("Now enter an age for " + currentLine + ": ");
ageList.add(input.nextInt());
}
System.out.print("\n");
for(int i = 0; i < MAX_VALUE; i++) {
System.out.println("Name: " + nameList.get(i) + " Age: " + ageList.get(i));
}
// DISPLAY YOUNGEST AND OLDEST OF ARRAY, PRODUCING ERRORS
int smallest = ageList.get(0);
int largest = ageList.get(0);
String oldest = nameList.get(0);
String youngest = nameList.get(0);
for (int i = 0; i < ages.length; i++) {
if(ageList.get(i) > largest) {
largest = ageList.get(i);
oldest = nameList.get(i);
}
else if(ageList.get(i) < smallest) {
smallest = ageList.get(i);
youngest = nameList.get(i);
}
}
System.out.println("\nThe youngest person is " + youngest + " who is " + smallest + " years old");
System.out.println("The oldest person is " + oldest + " who is " + largest + " years old");
}
}
正規表現はおそらく最も単純なものです。 – SomeJavaGuy
2台のスキャナーは必要ありません。確認http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – TheLostMind