Fix my code to only use the essential knowledge below for arrays:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class DaycareStatistics {
public static void main(String[] args) {
// Step 1: Read file and put into arrays
String[] rows;
int numOfLines = 0;
code
Assistant
User
is this encompassed by the essential knowledge statements 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;
}
Assistant
Yes, the calculateWeeklyIncome method, as written, follows array knowledge as defined by the essential knowledge statements:
It uses an indexed for loop to traverse an array (VAR-2.B.2 and VAR-2.B.3).
It efficiently accesses elements in an array using square brackets and an index, as described in VAR-2.A.6.
It includes a control structure (switch statement) that operates on array elements based on their values, calculating sums which are common array operations as noted in CON-2.I.1.
These operations are part of standard array algorithms and traversals that include computations of a sum, and such algorithms are included within the stipulated essential knowledge statements.
The code loops through each entry of the ages array and corresponding days array once, and modifies the primitive local variable income through accumulation. Accessing array elements and performing arithmetic operations on them are both core elements of array operations, so the function is consistent with the expected knowledge.
try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line = br.readLine();
// Determine how many lines
while (line != null) {
numOfLines++;
line = br.readLine();
}
br.close();
rows = new String[numOfLines];
// Makes each row into an array with the appropriate amount of storage space.
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;
}
// Step 2: Make arrays of your data
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];
}
// Task 1: Display student names
System.out.println("Student Names:");
for (String studentName : names) {
System.out.println(studentName);
}
System.out.println("\n----------------------------------\n");
// Task 2: Display average age of female and male children
displayAverageAges(ages, gender);
System.out.println("\n----------------------------------\n");
// Task 3: Display how many students are from each of the towns with a histogram
displayTownHistogram(hometown);
System.out.println("\n----------------------------------\n");
// Task 4: How much does the daycare make in income in one week?
int income = calculateWeeklyIncome(ages, days);
System.out.println("Weekly Income: $" + income);
System.out.println("\n----------------------------------\n");
// Task 6: Sort the students' names by last name
sortStudentsByLastName(names, ages, gender, hometown, days, number);
System.out.println("\nSorted Names:");
for (String studentName : names) {
System.out.println(studentName);
}
// Task 5: Look up phone number given a student's name.
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) {
Map<String, Integer> townHistogram = new HashMap<>();
for (String town : hometown) {
townHistogram.put(town, townHistogram.getOrDefault(town, 0) + 1);
}
System.out.println("Students per Hometown:");
for (Map.Entry<String, Integer> entry : townHistogram.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
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);
}
// Helper method to swap elements in arrays
private static void swap(Object[] array, int index1, int index2) {
Object 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;
}
}
VAR-2.A.1
The use of array objects allows multiple related
items to be represented using a single variable.
VAR-2.A.2
The size of an array is established at the time of
creation and cannot be changed.
VAR-2.A.3
Arrays can store either primitive data or object
reference data.
VAR-2.A.4
When an array is created using the keyword
new, all of its elements are initialized with a
specific value based on the type of elements:
§ Elements of type int are initialized to 0
§ Elements of type double are initialized to 0.0
§ Elements of type boolean are initialized
to false
§ Elements of a reference type are initialized
to the reference value null. No objects are
automatically created
VAR-2.A.5
Initializer lists can be used to create and
initialize arrays.
VAR-2.A.6
Square brackets ([ ]) are used to access and
modify an element in a 1D array using an index.
VAR-2.A.7
The valid index values for an array are
0 through one less than the number of
elements in the array, inclusive. Using an index
value outside of this range will result in an
ArrayIndexOutOfBoundsException
being thrown.
VAR-2.B.1
Iteration statements can be used to access
all the elements in an array. This is called
traversing the array.
VAR-2.B.2
Traversing an array with an indexed for
loop or while loop requires elements to be
accessed using their indices.
VAR-2.B.3
Since the indices for an array start at
0 and end at the number of elements
−1, “off by one” errors are easy to make
when traversing an array, resulting in an
ArrayIndexOutOfBoundsException
being thrown.
VAR-2.C.1
An enhanced for loop header includes a
variable, referred to as the enhanced for
loop variable.
VAR-2.C.2
For each iteration of the enhanced for loop,
the enhanced for loop variable is assigned a
copy of an element without using its index.
VAR-2.C.3
Assigning a new value to the enhanced for
loop variable does not change the value stored
in the array.
VAR-2.C.4
Program code written using an enhanced for
loop to traverse and access elements in an
array can be rewritten using an indexed for
loop or a while loop
CON-2.I.1
There are standard algorithms that utilize array
traversals to:
§ Determine a minimum or maximum value
§ Compute a sum, average, or mode
§ Determine if at least one element has a
particular property
§ Determine if all elements have a particular
property
§ Access all consecutive pairs of elements
§ Determine the presence or absence of
duplicate elements
§ Determine the number of elements meeting
specific criteria
CON-2.I.2
There are standard array algorithms that utilize
traversals to:
§ Shift or rotate elements left or right
§ Reverse the order of the elements
To modify your code to use only the essential array knowledge outlined, we can make some adjustments:
Eliminate the use of HashMap and create a simple method to count the number of students per hometown with nested loops instead.
Update the swapping method to handle primitives and String arrays directly, letting go of the generic Object[] swap.
Rewrite enhanced for loops as indexed for loops where we need to modify elements in place.
Here is the revised version of your code:
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class DaycareStatistics {
public static void main(String[] args) {
// Step 1: Read file and put into arrays
String[] rows;
int numOfLines = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line = br.readLine();
// Determine how many lines
while (line != null) {
numOfLines++;
line = br.readLine();
}
br.close();
rows = new String[numOfLines];
// Fill the rows array with data from the file.
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;
}
// Step 2: Make arrays of your data
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];
}
// Task 1: Display student names
// (Unchanged, since the enhanced loop is used for display purposes only and does not modify the array)
System.out.println("Student Names:");
for (String studentName : names) {
System.out.println(studentName);
}
System.out.println("\n----------------------------------\n");
// Task 2: Display average age of female and male children
// (Unchanged)
displayAverageAges(ages, gender);
System.out.println("\n----------------------------------\n");
// Task 3: Display how many students are from each of the towns with a histogram
// Modify this block to avoid using HashMap
displayTownHistogram(hometown);
System.out.println("\n----------------------------------\n");
// Task 4: How much does the daycare make in income in one week?
// (Unchanged)
int income = calculateWeeklyIncome(ages, days);
System.out.println("Weekly Income: $" + income);
System.out.println("\n----------------------------------\n");
// Task 6: Sort the students' names by last name
// (Unchanged)
sortStudentsByLastName(names, ages, gender, hometown, days, number);
System.out.println("\nSorted Names:");
for (String studentName : names) {
System.out.println(studentName);
}
// Task 5: Look up phone number given a student's name.
// (Unchanged)
System.out.println("\n----------------------------------\n");
lookupPhoneNumber(names, number);
System.out.println("\n----------------------------------\n");
}
// Task 2 helper method (Unchanged)
private static void displayAverageAges(int[] ages, String[] gender) {
// Code unchanged as it adheres to array knowledge specified.
}
// Task 3 helper method, modified to not use HashMap
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; // Mark as counted
}
}
System.out.println(hometown[i] + ": " + count);
}
}
}
// Task 4 helper method (Unchanged)
private static int calculateWeeklyIncome(int[] ages, int[] days) {
// Code unchanged as it adheres to array knowledge specified.
}
// Task 5 helper method (Unchanged)
private static void lookupPhoneNumber(String[] names, String[] number) {
// Code unchanged as it adheres to array knowledge specified.
}
// Task 6 helper method (Unchanged)
private static void sortStudentsByLastName(String[] names, int[] ages, String[] gender, String[] hometown, int[] days, String[] number) {
// Code unchanged as it adheres to array knowledge specified.
}
// Helper methods for swapping (simplified to specifically handle primitive and String arrays)
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;
}
}
In this version, the enhancements include:
Replacing the Map in displayTownHistogram with a simple approach that uses nested loops to count occurrences and null to mark elements that have already been counted.
Retained the existing tasks that already conform to the array knowledge restrictions. Methods such as displayAverageAges and lookupPhoneNumber do not require changes.
The swap helper methods were kept specific for String and int types.
This code should now adhere to the constraints based on the essential knowledge you've provided. Please note that this modification eliminates the histogram's consistent ordering since a Map typically handles the ordering of keys. If this is important, you would need to implement a sorting algorithm for town names as well.