ArrayList
in Java)
.length
field of the array doesn't represent the number of elements
in the array being used, but rather the number of elements actually allocated at array creation time.
size
) needs to be introduced, containing the number of elements in the array
actually being used (30 in the above example).
.length
in the context where the numbers of elements created differs from
the number of elements used.
"numbers.text"
, and prints
out each number together with whether it is above or below the average of the numbers. Assume a maximum of 100 numbers in the file
import java.io.*; import java.util.*; public class Program_14_1 { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("numbers.text")); final int CAPACITY = 100; int [] arr = new int[CAPACITY]; int size = read(scanner, arr, CAPACITY); double average = getAverage(arr, size); //for (int num : arr) for (int i = 0; i < size; i++) System.out.println(arr[i] + " is " + (arr[i] < average ? "below" : "above") + " average"); } public static int read(Scanner scanner, int [] arr, int capacity) { int size = 0; while (scanner.hasNextInt()) { if (size >= capacity) { System.out.println("Capacity exceeded - increase the size of your arrya"); System.exit(1); } arr[size] = scanner.nextInt(); size++; } return size; } public static double getAverage(int [] arr, int size) { return (double)getSum(arr, size)/size; } public static double getSum(int [] arr, int size) { int total = 0; for (int i = 0; i < size; i++) total += arr[i]; return total; } }
final
variable CAPACITY
read
method accepts the Scanner
, array, and capacity, and returns the logical size of the array (again, see below)
read
contains logic to prevent array overflow
ArrayBoundsException
length
field of the array (the physical size) is inappropriate for most subsequent processing; it includes elements that have not been populated
size
parameter of getAverahe
and getSum
size
must be passed as an argument to functions working with the array
// using eof final static int CAPACITY = 100; double [] arr = new double[CAPACITY]; int size = 0; while (scanner.hasNextInt()) { arr[size] = scanner.nextInt(); size++; } // size now contains the actual number of elements read into the array
// using a trailer of -1 final static int CAPACITY = 100; double [] arr = new double[CAPACITY]; int size = 0; arr[size] = scanner.nextInt(); // priming the pump while (arr[size] >= 0) { size++; arr[size] = scanner.nextInt(); } // size now contains the actual number of elements read into the array
// Notice the second parameter void print(double [] arr, int size) { System.out.print("{"); for (int i = 0; i < size; i++) System.out.print(arr[i]+ " "); System.out.print("}"); }
.length
field
double [] resize(double [] arr) { double [] tmpArr = new double[arr.length * 2]; for (int i = 0; i < arr.length; i++) tmpArr[i] = arr[i]; return tmpArr; }
double [] arr = new double[…]; … arr = resize(arr);
As we've seen, our programs often manipulate several pieces of information in performing their task:
The program should define the following methods:
int read(Scanner scanner, String [] names, int [] midterms, int [] finalExams, int capacity);
void print(String [] names, int [] midterms, int [] finalExams, int size);
import java.io.*; import java.util.*; public class Program_14_2 { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("exams.text")); final int CAPACITY = 100; String [] names = new String[CAPACITY]; int [] midterms = new int[CAPACITY], finalExams = new int[CAPACITY]; int size = read(scanner, names, midterms, finalExams, CAPACITY); print(names, midterms, finalExams, size); } public static int read(Scanner scanner, String [] names, int [] midterms, int [] finalExams, int capacity) { int size = 0; while (scanner.hasNext()) { if (size >= capacity) { System.out.println("Capacity exceeded - increase the size of your arrya"); System.exit(1); } names[size] = scanner.next(); midterms[size] = scanner.nextInt(); finalExams[size] = scanner.nextInt(); size++; } return size; } public static void print(String [] names, int [] midterms, int [] finalExams, int size) { System.out.println("Received at least one 90 or above"); for (int i = 0; i < size; i++) if (midterms[i] >= 90 || finalExams[i] >= 90) System.out.println(names[i] + " " + midterms[i] + " " + finalExams[i]); System.out.println(); System.out.println("Rest of the class"); for (int i = 0; i < size; i++) if (midterms[i] < 90 && finalExams[i] < 90) System.out.println(names[i] + " " + midterms[i] + " " + finalExams[i]); } }
The program should define the following methods:
int read(String fname, String [] lastNames[], String [] firstNames, int [] midterms, int [] finals, int capacity);
void calcAverages(int [] midterms, int [] finals, double [] averages, int size)
double calcOneAverage(int midterm, int final)
double calcClassAverage(double [] averages, int size)
void calcGrades(double [] averages, char [] grades, int size)
char calcOneGrade(double average)
void printRoster(String [] lastNames, String [] firstNames, int [] midterms, int [] finals,
double [] averages, char [] grades, int size, double classAverage)
void printOneStudent(String lastName, String firstName, int midterm, int final,
double average, char grade, classAverage)
import java.io.*; import java.util.*; public class Program_14_3 { public static void main(String [] args) throws Exception { Scanner keyboard = new Scanner(System.in); System.out.print("roster file? "); String filename = keyboard.next(); final int CAPACITY = 100; String [] lastNames = new String[CAPACITY], firstNames = new String[CAPACITY]; int [] midterms = new int[CAPACITY], finals = new int[CAPACITY]; double [] averages = new double[CAPACITY]; char [] grades = new char[CAPACITY]; int size = read(filename, lastNames, firstNames, midterms, finals, CAPACITY); calculateAverages(midterms, finals, averages, size); double classAverage = calculateClassAverage(averages, size); calculateGrades(averages, grades, size); printRoster(lastNames, firstNames, averages, grades, classAverage, size); } public static int read(String filename, String [] lastNames, String [] firstNames, int [] midterms, int [] finals, int capacity) throws Exception { Scanner scanner = new Scanner(new File(filename)); int size = 0; while (scanner.hasNext()) { if (size >= capacity) { System.out.print("Reached array capacity and still more data. Make the array bigger"); System.exit(1); } lastNames[size] = scanner.next(); firstNames[size] = scanner.next(); midterms[size] = scanner.nextInt(); finals[size] = scanner.nextInt(); size++; } return size; } public static void calculateAverages(int [] midterms, int [] finals, double [] averages, int size) { for (int i = 0; i < size; i++) averages[i] = calculateOneAverage(midterms[i], finals[i]); } public static double calculateOneAverage(int midterm, int finalExam) {return (midterm + finalExam)/2.0;} public static double calculateClassAverage(double [] averages, int size) { double total = 0; for (int i = 0; i < size; i++) total += averages[i]; return total / size; } public static void calculateGrades(double [] averages, char [] grades, int size) { for (int i = 0; i < size; i++) grades[i] = calculateOneGrade(averages[i]); } public static char calculateOneGrade(double average) { return average >= 90 ? 'A' : average >= 80 ? 'B' : average >= 70 ? 'C' : average >= 60 ? 'D' : 'F'; } public static void printRoster(String [] lastNames, String [] firstNames, double [] averages, char [] grades, double classAverage, int size) { for (int i = 0; i < size; i++) printOneStudent(lastNames[i], firstNames[i], averages[i], grades[i], classAverage); } public static void printOneStudent(String lastName, String firstName, double average, char grade, double classAverage) { System.out.println(lastName + " " + firstName + " " + average + " " + grade + " " + (average >= classAverage ? "Above" : "Below")); } }
Using Arrays:
import java.io.*; import java.util.*; public class Program_14_3 { public static void main(String [] args) throws Exception { Scanner keyboard = new Scanner(System.in); System.out.print("roster file? "); String filename = keyboard.next(); final int CAPACITY = 100; Student [] students = new Student[CAPACITY]; int size = read(filename, students, CAPACITY); double classAverage = calculateClassAverage(students, size); printRoster(students, size, classAverage); } public static int read(String filename, Student [] students, int capacity) throws IOException { Scanner scanner = new Scanner(new File(filename)); int size = 0; while (scanner.hasNext()) { if (size >= capacity) { System.out.print("Reached array capacity and still more data. Make the array bigger"); System.exit(1); } String lastName = scanner.next(); String firstName = scanner.next(); int midterm = scanner.nextInt(); int finalExam = scanner.nextInt(); students[size] = new Student(lastName, firstName, midterm, finalExam); size++; } return size; } public static double calculateClassAverage(Student [] students, int size) { double total = 0; for (int i = 0; i < size; i++) total += students[i].average; return total / size; } public static void printRoster(Student [] students, int size, double classAverage) { for (int i = 0; i < size; i++) System.out.println(students[i] + " " + (students[i].average >= classAverage ? "Above" : "Below")); } } class Student { Student(String last, String first, int mid, int fin) { lastName = last; firstName = first; midterm = mid; finalExam = fin; average = (midterm + finalExam) / 2.0; grade = average >= 90 ? 'A' : average >= 80 ? 'B' : average >= 70 ? 'C' : average >= 60 ? 'D' : 'F'; } public String toString() {return lastName + " " + firstName + " " + average + " " + grade;} String lastName, firstName; int midterm, finalExam; double average; char grade; }
for
loop header in the print
method of Program_14.4
below).
The program should define and call the following methods:
int [] read(Scanner scanner)
void print(int [] arr);
void print(int [] arr, int first, int end)
.
import java.io.*; import java.util.*; public class Program_14_4 { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(new File("numbers.text")); int [] arr = read(scanner); print(arr); System.out.println(); Scanner keyboard = new Scanner(System.in); System.out.print("First index to print: "); int first = keyboard.nextInt(); System.out.print("Last index to print: "); int last = keyboard.nextInt(); print(arr, first, last+1); System.out.println(); } public static int [] read(Scanner scanner) { int size = scanner.nextInt(); int [] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = scanner.nextInt(); return arr; } public static void print(int [] arr) { System.out.print("{"); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + (i < arr.length-1 ? ", " : "")); System.out.print("}"); } public static void print(int [] arr, int first, int end) { for (int i = first; i < end; i++) System.out.print(arr[i] + (i < end-1 ? ", " : "")); } }
void print(int [] arr, int first, int end)
first, we can the easily implement the method
void print(int [] arr)
:
void print(int [] arr) {print(arr, 0, arr.length);}