我的任务要求我制作一个犯罪记录程序,提示用户输入犯罪姓名、犯罪和定罪年份,然后它会使用另一个类(数据库)将其存储在一个数组中。该类如下所示:
class Database {
String name;
String crime;
int year;
}
我做了一个方法来输入我的信息,但是当我测试它以显示列表时,它只显示了我输入的最后一个罪犯。为什么要这样做?
//method to input criminal records
public static void inputData() throws IOException {
arr = new Database[3];
Database temp = new Database();
for(int i = 0; i < arr.length; i++){
System.out.print("Enter criminal first and last name: ");
String name = br.readLine();
temp.name = name;
System.out.print("Enter crime: ");
String crime = br.readLine();
temp.crime = crime;
System.out.print("Enter the year of conviction: ");
int year = Integer.valueOf(br.readLine()).intValue();
temp.year = year;
// Copy the name, crime, year to the global variables
arr[i] = temp;
System.out.println(arr[i].name + " was convicted in the year " + arr[i].year + " for " + arr[i].crime + ".");
}
}
我还需要根据用户输入的关键字(犯罪类型)进行顺序搜索,然后显示犯下该类型犯罪的罪犯。这是搜索的方法:
//method to search data
public static int searchData() throws IOException{
System.out.print("Which crime would you like to select? (arson, theft, assault) ");
String searchKey = br.readLine();
for (int i = 0; i < arr.length; i++){
if (arr[i].crime.equals(searchKey)){
return i; //found it!
}
}
//key was not found
return -1;
}
我的老师在解释方面很糟糕,所以我对顺序搜索进行了研究,但我仍然无法弄清楚如何让它显示犯下该罪行的罪犯名单。