更新<!/强> 我现在已经修复了原始问题,但结果是显示最年轻和最老的成员时出错并抛出以下错误。有什么建议?感谢
线程“main”中的异常java.lang.IndexOutOfBoundsException:索引:4,大小:4 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at 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");
}
}
答案 0 :(得分:2)
正如评论所示,我会在这里使用两个正则表达式,一个用于名称,一个用于年龄。另外,我会将扫描仪的输入作为字符串。目前,您正在调用Scanner.nextInt()
,我认为这对于非数字数据会失败。如果发生这种情况,您的正常应用程序逻辑将检查输入是否永远不会被命中。相反,将它们都读为字符串,然后使用正则表达式来验证输入的格式。
这样的事情应该有效:
String age = "35";
String name = "Tim Biegeleisen";
if (name.matches(".*[^a-zA-Z].*")) {
System.out.println("Not a valid name");
}
if (age.matches(".*[^0-9].*")) {
System.out.println("Not a valid age");
}
答案 1 :(得分:1)
java.util.regex.Pattern
(https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)的javadoc。
name.matches("\\D+") // for anything other than numbers with length > 1
name.matches("\\d+") // for numbers of length 1 and more