Skip to content

Instantly share code, notes, and snippets.

@bricker
Created March 19, 2017 06:55
Show Gist options
  • Save bricker/964d07b2965c9b1550855964f943cd82 to your computer and use it in GitHub Desktop.
Save bricker/964d07b2965c9b1550855964f943cd82 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
/**
* Bryan Ricker
* CS130 Lab #3
*/
public class TwoDArrayOperations {
public static void main(String[] args) throws IOException {
double[][] table = loadArray(args[0]);
for (int i = 0; i < table.length; i++) {
System.out.println(getRowTotal(table, i));
}
for (int i = 0; i < table[0].length; i++) {
System.out.println(getColumnTotal(table, i));
}
System.out.println(getTotal(table));
}
public static double[][] loadArray(String filename) throws IOException {
Scanner inputFile = new Scanner(new File(filename));
int lineCount = 0;
int colCount = 0;
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
int len = line.split(" ").length;
if (len > colCount) colCount = len;
lineCount++;
}
inputFile.close();
double[][] result = new double[lineCount][colCount];
inputFile = new Scanner(new File(filename));
for (int row = 0; row < lineCount; row++) {
for (int col = 0; col < colCount; col++) {
result[row][col] = inputFile.nextDouble();
}
}
inputFile.close();
return result;
}
public static double getTotal(double[][] table) {
double total = 0.0;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
total += table[i][j];
}
}
return total;
}
public static double getAverage(double[][] table) {
int len = 0;
for (int i = 0; i < table.length; i++) {
len += table[i].length;
}
return getTotal(table) / len;
}
public static double getRowTotal(double[][] table, int row) {
double total = 0.0;
for (int i = 0; i < table[row].length; i++) {
total += table[row][i];
}
return total;
}
public static double getColumnTotal(double[][] table, int column) {
double total = 0.0;
for (int i = 0; i < table.length; i++) {
total += table[i][column];
}
return total;
}
public static double getHighestInRow(double[][] table, int row) {
double highest = table[row][0];
for (int i = 0; i < table[row].length; i++) {
double num = table[row][i];
if (num > highest) {
highest = num;
}
}
return highest;
}
public static double getLowestInRow(double[][] table, int row) {
double lowest = table[row][0];
for (int i = 0; i < table[row].length; i++) {
double num = table[row][i];
if (num < lowest) {
lowest = num;
}
}
return lowest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment