try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line = br.readLine();
while (line != null) {
numOfLines++;
line = br.readLine();
}
br.close();
rows = new String[numOfLines];
BufferedReader br2 = new BufferedReader(new FileReader("data.txt"));
int i = 0;
line = br2.readLine();
while (line != null) {
rows[i] = line;
line = br2.readLine();
i++;
}
br2.close();
} catch (IOException e) {
System.out.println("An error has occurred");
return;
}
String[] names = new String[numOfLines];
int[] ages = new int[numOfLines];
String[] gender = new String[numOfLines];
String[] hometown = new String[numOfLines];
int[] days = new int[numOfLines];
String[] number = new String[numOfLines];
for (int j = 0; j < rows.length; j++) {
String[] splitData = rows[j].split(",");
names[j] = splitData[0];
ages[j] = Integer.parseInt(splitData[1]);
gender[j] = splitData[2];
hometown[j] = splitData[3];
days[j] = Integer.parseInt(splitData[4]);
number[j] = splitData[5];
}
System.out.println("Student Names:");
for (String studentName : names) {
System.out.println(studentName);
}
System.out.println("\n----------------------------------\n");
displayAverageAges(ages, gender);
System.out.println("\n----------------------------------\n");
displayTownHistogram(hometown);
System.out.println("\n----------------------------------\n");
int income = calculateWeeklyIncome(ages, days);
System.out.println("Weekly Income: $" + income);
System.out.println("\n----------------------------------\n");
sortStudentsByLastName(names, ages, gender, hometown, days, number);
System.out.println("\nSorted Names:");
for (String studentName : names) {
System.out.println(studentName);
}
System.out.println("\n----------------------------------\n");
lookupPhoneNumber(names, number);
System.out.println("\n----------------------------------\n");
}
private static void displayAverageAges(int[] ages, String[] gender) {
double femaleAgeSum = 0;
double maleAgeSum = 0;
int femaleCount = 0;
int maleCount = 0;
for (int i = 0; i < gender.length; i++) {
if ("F".equals(gender[i])) {
femaleAgeSum += ages[i];
femaleCount++;
} else if ("M".equals(gender[i])) {
maleAgeSum += ages[i];
maleCount++;
}
}
System.out.println("Average age of female children: " + (femaleCount > 0 ? femaleAgeSum / femaleCount : "N/A"));
System.out.println("Average age of male children: " + (maleCount > 0 ? maleAgeSum / maleCount : "N/A"));
}
private static void displayTownHistogram(String[] hometown) {
for (int i = 0; i < hometown.length; i++) {
int count = 1;
if (hometown[i] != null) {
for (int j = i + 1; j < hometown.length; j++) {
if (hometown[i].equals(hometown[j])) {
count++;
hometown[j] = null;
}
}
System.out.println(hometown[i] + ": " + count);
}
}
}
private static int calculateWeeklyIncome(int[] ages, int[] days) {
int income = 0;
for (int i = 0; i < ages.length; i++) {
switch (ages[i]) {
case 1:
income += 35 * days[i];
break;
case 2:
income += 30 * days[i];
break;
case 3:
income += 25 * days[i];
break;
case 4:
income += 20 * days[i];
break;
case 5:
income += 15 * days[i];
break;
}
}
return income;
}
private static void lookupPhoneNumber(String[] names, String[] number) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter student's name to look up phone number:");
String nameToFind = scanner.nextLine();
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(nameToFind)) {
System.out.println("Phone number for " + nameToFind + " is: " + number[i]);
scanner.close();
return;
}
}
System.out.println("Student not found.");
scanner.close();
}
private static void sortStudentsByLastName(String[] names, int[] ages, String[] gender, String[] hometown, int[] days, String[] number) {
boolean swapped;
do {
swapped = false;
for (int i = 1; i < names.length; i++) {
String lastName1 = names[i - 1].substring(names[i - 1].indexOf(' ') + 1);
String lastName2 = names[i].substring(names[i].indexOf(' ') + 1);
if (lastName1.compareTo(lastName2) > 0) {
swap(names, i - 1, i);
swap(ages, i - 1, i);
swap(gender, i - 1, i);
swap(hometown, i - 1, i);
swap(days, i - 1, i);
swap(number, i - 1, i);
swapped = true;
}
}
} while (swapped);
}
private static void swap(String[] array, int index1, int index2) {
String temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
private static void swap(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
There are several potential issues with the provided code which might cause it to not work properly or inefficiently:
-
Resource Leak:
Your initial BufferedReader (br) and Scanner (scanner) are closed properly, but in general practice, they should be used inside a try-with-resources statement for better exception handling and automatic resource management.
-
Assumptions about input file format:
You're assuming that each line in the data file data.txt is properly formatted and has exactly 6 values separated by commas. If any line doesn't follow this structure, you will get an ArrayIndexOutOfBoundsException when trying to access splitData[5] or any other index that doesn't exist.
-
Use of magic numbers in calculateWeeklyIncome:
The income calculation uses hardcoded age values. If the business logic changes, you'd have to update the switch statement. Consider removing the magic numbers and perhaps utilizing a data structure that maps ages to rates.
-
Inefficient processing of the file:
You're reading the file twice—first to count the number of lines and then to read the lines into an array. This is not necessary; you can use a List to just read the lines once and add each line to the list as you read it.
-
Closing Scanner can close System.in:
You are closing the scanner at the end of lookupPhoneNumber method which also closes the underlying input stream, System.in. If another part of the program tries to read from System.in after this method has been called, it will raise a NoSuchElementException because the input stream has been closed.
-
Potential for StringIndexOutOfBoundsException:
In sortStudentsByLastName you're assuming that every name contains a space. If there's a name with no space, names[i].indexOf(' ') will return -1 and you'll get a StringIndexOutOfBoundsException.
-
Logic in Sorting Method:
The logic for extracting last names in sortStudentsByLastName is iffy because it relies on names being in "First Last" format without any middle names, prefixes, or suffixes, and it doesn't handle the case when a name doesn't have a space character at all.
-
Hardcoding the filename:
The filename "data.txt" is hardcoded. It's usually better to pass filenames as arguments or read from a configuration so you don't have to recompile the program to read a different file.
To resolve these potential problems and improve the code, consider the following:
- Read the file contents just once into a List rather than an array, then convert to an array if needed.
- Guard against incorrectly formatted lines with appropriate error checking.
- Use Java's try-with-resources to ensure resources are closed properly.
- Address the hardcoded filename and magic numbers to make the code more flexible.
- Make sure to only close the Scanner wrapping
System.in when you're completely done using System.in in your application, or better yet use a single Scanner instance throughout your program and close it in the main method.
Remember that the functionality also depends on the definition of methods like displayAverageAges, displayTownHistogram, calculateWeeklyIncome, lookupPhoneNumber, and sortStudentsByLastName, as well as the data structure and content of "data.txt", so make sure these methods are also implemented correctly and that the data you're working with is valid.
The potential for the error arises when a line of the file does not have six comma-separated values. For example, if any line has less than six values, your code will throw an ArrayIndexOutOfBoundsException when trying to access splitData[5] or another index that doesn't exist.