This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I have an array thats supposed to be a size of 3 which takes in 3 dive totals. It takes in an array of 7 scores from a double []. I have used a test scenario to see if the diveScore() method works and the calculations are correct. But when i try to read the numbers from a file and put them into an array, the scoreArray that holds the calculated dive score for each dive fails to store the data. The scoreArray in my hard coded test case works fine. Here is the exception from the console when run. I have tried to look at the line where the error states but the test data that I commented out in the main file works fine with the 3 arrays of scores for each dive. What am I missing? Every for loop doesn't have <= in it like many articles have been shown to me by everyone.
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3
at Diver.diveScore(Diver.java:33)
at Main.readFile(Main.java:74)
at Main.main(Main.java:10)
Main File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Diver [] divers = new Diver[25];
int numDivers = readFile(divers);
System.out.println(numDivers);
/*Diver d = new Diver("Frank Stalteri", "Middlesex County College");
double [] scores = {6.2, 3.5, 8, 7.3, 6, 9.1, 4.8};
double [] scores2 = {7.4, 5.4, 8, 3.7, 2.5, 7.8, 4};
double [] scores3 = {4.6, 7.2, 7.3, 1.4, 3.6, 8, 4.7};
d.diveScore(1, scores, 2);
d.diveScore(2, scores2, 4);
d.diveScore(3, scores3, 3);
System.out.println(d.toString());
*/
}
public static int readFile(Diver [] divers) throws FileNotFoundException {
File f = new File("divers.dat");
Scanner kb = new Scanner(f);
Diver d;
int count = 0;
int diveNum = 1;
while (kb.hasNextLine()) {
String name = kb.nextLine();
String school = kb.nextLine();
String dive1 = kb.nextLine();
String dive2 = kb.nextLine();
String dive3 = kb.nextLine();
//String [] of size 8 (inlcudes the difficulty #)
String [] scores1 = dive1.split("\\s+");
String [] scores2 = dive2.split("\\s+");
String [] scores3 = dive3.split("\\s+");
//gets the difficulty from String [] then parses
double diff1 = Double.parseDouble(scores1[scores1.length - 1]);
double diff2 = Double.parseDouble(scores2[scores2.length - 1]);
double diff3 = Double.parseDouble(scores3[scores3.length - 1]);
//make new double [] of size 7
double [] scores1D = new double[scores1.length - 1];
double [] scores2D = new double[scores2.length - 1];
double [] scores3D = new double[scores3.length - 1];
//loops through String [] and casts numbers without difficulty number
for (int i = 0; i < scores1D.length; i++) {
scores1D[i] = Double.parseDouble(scores1[i]);
//System.out.println(scores1D[i]);
}
for (int i = 0; i < scores2D.length; i++) {
scores2D[i] = Double.parseDouble(scores2[i]);
//System.out.println(scores2D[i]);
}
for (int i = 0; i < scores3D.length; i++) {
scores3D[i] = Double.parseDouble(scores3[i]);
//System.out.println(scores3D[i]);
}
d = new Diver(name, school);
divers[count] = d;
count++;
d.diveScore(diveNum, scores1D, diff1);
diveNum++;
d.diveScore(diveNum, scores2D, diff2);
diveNum++;
d.diveScore(diveNum, scores3D, diff3);
//System.out.println(d.toString());
}
kb.close();
return count;
}
public static void printDivers(Diver [] divers, int numDivers) {
System.out.println("All Divers\n");
for (int i = 0; i < divers.length; i++) {
if (divers[i] != null) {
System.out.println(divers[i]);
}
}
}
}
Diver File:
public class Diver {
private String name;
private String school;
private double [] scoreArray = new double [3];
private double totalScore;
Diver() {
}
Diver(String name, String school) {
this.name = name;
this.school = school;
}
//loop through score array and calculate the total score for each dive attempt
public double [] diveScore(int diveNum, double [] scores, double difficulty) {
double min = min(scores);
double max = max(scores);
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
total -= max;
total -= min;
total *= difficulty;
scoreArray[diveNum - 1] = Math.round(total * 100.0) / 100.0;
return scoreArray;
}
//finds smallest score in array of scores
private double min(double [] scores) {
java.util.Arrays.parallelSort(scores);
double min = scores[0];
return min;
}
//finds largest score in array of scores
private double max(double [] scores) {
java.util.Arrays.parallelSort(scores);
double max = scores[scores.length - 1];
return max;
}
//calculates total of the 3 dives
public double totalScore() {
for (int i = 0; i < scoreArray.length; i++) {
totalScore += scoreArray[i];
}
return totalScore;
}
public String toString() {
String str = name + ", " + school + ": " + totalScore() + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
return str;
}
public boolean equals(Diver d) {
boolean value = true;
if (d == null || !(d instanceof Diver)) {
value = false;
return value;
}
Diver diver = (Diver) d;
if (this.totalScore == d.totalScore) {
value = true;
return value;
}
return value;
}
}
Your first diver must start at 0
Main > readFile > while loop
int diveNum = 0;
Related
How would I format my array as this? I've tried many different methods but I can't seem to get it to work.
I want it to return something like this
"Avg of 1 2 3 4 5 is 3.00"
public class AverageNumber {
private static int[] n = new int[5];
private static double total = 0;
public static void main(String[] a) {
AverageNumber object = new AverageNumber();
object.Dialogue();
}
private void Dialogue() {
int count = 1;
System.out.println("Skriv inn 5 tall" + count++);
for(int i=0; i<n.length; i++){
n[i] = Konsoll.readInt("Tall");
total = total + n[i];
}
double avg = total / n.length;
System.out.println("Avg of " + formatArray() + " is " + avg);
}
private static double formatArray() {
//Return all numbers
}
}
formatArray method should return String, like this :
private static String formatArray() {
String s = "";
for(int i = 0 ; i < n.length ; i++)
s+= String.valueOf(n[i])+" ";
return s;
}
Place code to print elements from arr_param
Place code to sort elements in arr_param in ascending order of fahrenheit temperature
Place code to print out elements from arr_param with temperatures > 90 deg. F
There is a private class to do the conversions from F to C to K.
public class Temperature {
public Temperature(double p_fahren) {
fahrenTemp = p_fahren;
}
public void setFahrenheit(double p_fahren) {
fahrenTemp = p_fahren;
}
public double getFahrenheit() {
return fahrenTemp;
}
public double getCelsius() {
double celsius_temp;
celsius_temp = (5.0 / 9.0) * (fahrenTemp - 32.0);
return celsius_temp;
}
public double getKelvin() {
double kelvin_temp = ((5.0 / 9.0) * (fahrenTemp - 32.0)) + 273.0;
return kelvin_temp;
}
public String toString() {
String ret_val = "";
ret_val = String.format("%.1f F, %.1f C, %.1f K",fahrenTemp, getCelsius(), getKelvin());
return ret_val;
}
}
We are not allowed to use the Arrays Util
public class Asn5_Test_Temperature
{
public static void main(String args[])
{
Temperature arr_temps [] =
{
new Temperature(90), new Temperature(75), new Temperature(65), new Temperature(95),
new Temperature(89), new Temperature(67), new Temperature(77), new Temperature(71),
new Temperature(55), new Temperature(65), new Temperature(64), new Temperature(74),
new Temperature(91), new Temperature(86), new Temperature(78), new Temperature(73),
new Temperature(68), new Temperature(94), new Temperature(91), new Temperature(62)
};
print_array("After population", arr_temps);
sort_array(arr_temps);
print_array("After sort", arr_temps);
print_days_above_90(arr_temps);
}
public static void print_array(String message, Temperature arr_param[])
{
System.out.println("----" + message + "---");
for(Temperature oneElem : arr_param)
System.out.print(oneElem + "\t");
System.out.println();
}
public static void sort_array(Temperature arr_param[])
{
int min;
int temp = 0;
for(int i = 0; i < arr_param.length; i++)
{
min = i;
for(int j = i + 1; j < arr_param.length; j++)
{
if(arr_param[j] < arr_param[min])
{
min = j;
}
}
temp = arr_param[i];
arr_param[i] = arr_param[min];
arr_param[min] = temp;
}
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i] + " ");
}
}
public static void print_days_above_90(Temperature arr_param[])
{
System.out.println("----Days over 90 F---");
for(int i = 0; i > 90; i++)
{
System.out.print(arr_param[i] + " ");
}
}
}
The program is supposed to print out the array, then in ascending order, then only the ones that are above 90 degrees F
I am having issue getting the sort code to work and getting it to sort the temperatures over 90 degrees F. I get three errors in my code: error: bad operand types for binary operator '<' and error: incompatible types: Temperature cannot be converted to int and error: incompatible types: int cannot be converted to Temperature
For this section call the getFahrenheit method to compare:
if(arr_param[j].getFahrenheit() < arr_param[min].getFahrenheit())
{
min = j;
}
For this section.. use the toString method. The purpose of the toString method is to convert your object data to a readable String.
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i].toString() + " ");
}
I hope this helps and let me know if you have any questions.
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
so I have a program that takes a txt file and is read in and uses the class of another java file to set up the array. I am trying use selection sort to sort the values placed into the array but it gives me bad operand types for the line: (if array[j] < array[min]). The text file used is:"Country" "Total CO2 2005 (million tonnes)" "Road CO2 (million tonnes)" "Road CO2 per person (tonnes)" "Cars per 1000 people"
10
USA 5951.13 1530.3 5.16 777
UK 2573.4 119.68 1.99 470
Italy 476.08 116.86 2 592
Germany 841.78 150.21 1.82 550
Canada 553.02 123.42 3.82 562
France 414.03 128.13 2.04 477
Russia 1575.44 114.69 0.8 178
Japan 1254.47 224.24 1.76 447
China 5100.6 228.02 0.3 17
India 1147.46 91.06 0.1 8
The program with the class being called carbonDioxide.java:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
The program I am writing calling the two above, CarbonAnalysis.java:
import java.io.*;
import java.util.*;
public class CarbonAnalysis {
public static void main(String[]args){
//CarbonDioxideData c1 = new CarbonDioxideData();
//c1.setCountry("canada");
//System.out.println(c1);
Scanner userInput = new Scanner(System.in);
String fileName ="";
File inputFile = null;
Scanner fileReader = null;
while(fileReader==null){
try{
System.out.println("Enter input file name:");
fileName= userInput.next();
inputFile = new File(fileName);
fileReader = new Scanner(inputFile);
System.out.println("Successfully opening " + fileName);
}catch(IOException err){
System.out.println("Something went wrong");
System.out.println(err);
System.out.println("Please retry");
}
}
String testLine = fileReader.nextLine();
System.out.println(testLine);
int numberOfEntries = fileReader.nextInt();
System.out.println(numberOfEntries);
CarbonDioxideData[] array = new CarbonDioxideData[numberOfEntries];
for(int i =0;i<numberOfEntries;i++){
CarbonDioxideData c1 = new CarbonDioxideData();
String country = fileReader.next();
c1.setCountry(country);
double totalCO2 = fileReader.nextDouble();
c1.setTotalCO2(totalCO2);
double roadCO2 = fileReader.nextDouble();
c1.setRoadCO2(roadCO2);
double perPerson = fileReader.nextDouble();
c1.setCO2PerPerson(perPerson);
int cars = fileReader.nextInt();
c1.setCarsPerPerson(cars);
//System.out.println(c1);
array[i]=c1;
}
printArray(array);
emissionStats(array);
}
public static void printArray(CarbonDioxideData[] a){
for(int i=0; i<a.length;i++){
System.out.println(a[i]);
}
}
public static void emissionStats(CarbonDioxideData[] array){
for (int i = 0; i < array.length - 1; i++) {
// find index of smallest remaining value
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
// swap smallest value its proper place, a[i]
swap(array, i, min);
}
}
public static void swap(CarbonDioxideData[] a, int i, int j) {
if (i != j) {
CarbonDioxideData temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
The error I am receiving when compiling:
CarbonAnalysis.java:68: error: bad operand types for binary operator '<'
if array[j] < array[min]
first type: CarbonDioxideData
Second type: CarbondDioxidedata
I am at a loss I have no idea how to get it to work. Any help appreciated
< , > binary operators can be used with primitive types.
public class CarbonDioxideData implements Comparable<CarbonDioxideData> {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
#Override
public int compareTo(CarbonDioxideData that) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == that) return EQUAL;
//Compare function according to your logic
if (this.totalCO2 == that.totalCO2) return EQUAL;
if (this.totalCO2 > that.totalCO2)
return AFTER;
else
return BEFORE;
}
}
Your comparison should be as
if (array[j].compareTo(array[min]) < 0) {
min = j;
}
I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.