I have 2 arrays, String[][] names and int[][] grades, to store the names and grades of a class I am trying to print as a table in a much longer code. I was able to calculate the average of each row with a method I called in the main. I'm having a hard time figuring out how to do the average of each column though. Any suggestions would be appreciated. For the row averages I wrote a method:
//determine average for each student
public double rowAverage(int[] rowOfGrades) {
int total = 0;
//sum grades for each student
for(int grade : rowOfGrades){
total += grade;
}
//return average of student grades
return (double) total/rowOfGrades.length;
}//end getAverage
and then printed it in my main with
//creates rows and columns of text for array names and grades
for(int student=0; student<names.length; student++) {
System.out.printf("%s",names[student]); //student name
for(int test : grades[student]) {
System.out.printf("\t%7d",test); //test grades
}
//call method getAverage to calculate students grade average
//pass row of grades as the argument to getAverage
double average = rowAverage(grades[student]);
System.out.printf("%12.2f", average);
}
For each test you have to iterate over the students:
for (int test = 0; test < grades.length; test++) {
int total = 0;
for(int student=0; student<names.length; student++) {
total += grades[student][test]
}
double avgForTest = (double) total/names.length;
}
Make a new array w/ the values for the column you are interested in; rowAverage will compute the average for that array (thus that column). Repeat for each column.
to access each column of a row you will have to access its length field e.g. names[student].length
example
int[][] towers = new int[8][8];
int myNumber=25;
for(int row=0;row<towers.length;++row)
{
for(int column=0;column<towers[row].length;++column)
{
if(myNumber==towers[row][column])
{
System.out.println("I found you");
column=towers[row].length;
row=towers.length;
}
}
}
You can try like
for (int i = 0; i < 2; i++) {
int rowSum = 0;
int colSum = 0;
double rowAvg = 0.0;
double colAvg = 0.0;
for (int j = 0; j < 2; j++) {
rowSum += arr[i][j];
colSum += arr[j][i];
}
rowAvg = rowSum / 2.0;
colAvg = colSum / 2.0;
System.out.println(i + " row average: " + rowAvg);
System.out.println(i + " column average: " + colAvg);
}
Related
I have a program where i have to find the average for each student score from a text file and display it as a 2D array.
I am stuck - all I accomplish every time is getting the average for each row or column, but i have to find the average for each value in the text file.
For example: 76 / 48 = 1.5 (rounding off to 1 decimal)
Here my code:
public void studentAverage(double average) throws
FileNotFoundException
{
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
//Im stucked here
rowNum += arr[row][col];
}
average = rowNum / arr[row].length;
System.out.println("StudentAverage is: "+average);
rowNum = 0;
}
}
The average for each value in the entire grid is just a single number (I think). So, all you need to is to take the running sum and then divide by the number of cells:
double sum = 0.0d;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
}
int size = arr.length*arr[0].length;
double average = sum / size;
System.out.println("StudentAverage is: " + average);
In my calculation of the size, which is the total number of students, I am assuming that your 2D array is not jagged. That is, I assume that each row has the same number of columns' worth of data.
You could use streams for this.
To get the overall average
double average = Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.average();
And to get the average per row:
double[] averagePerRow = Ararys.stream(arr)
.map(Arrays::stream)
.mapToDouble(IntStream::average)
.toArray();
This works for any 2D int array, jagged or not.
I would use List for this
public void studentAverage() throws FileNotFoundException {
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
List<List<Integer>> grades = new ArrayList<>();
double totalCount = 0.0;
while (sc.hasNext()) {
List<Integer> row = new ArrayList<>();
Scanner lineScanner= new Scanner(sc.nextLine());
while (lineScanner.hasNextInt()) {
row.add(lineScanner.nextInt());
}
grades.add(row);
totalCount += row.size();
}
int index = 0;
for (List<Integer> list : grades) {
for (Integer grade : list) {
System.out.println("Student average is " + (double)Math.round(grade.doubleValue() / totalCount * 10) / 10);
}
}
}
Check this Link - How to find average of elements in 2d array JAVA?
public class AverageElements {
private static double[][] array;
public static void main (String[] args){
// Initialize array
initializeArray();
// Calculate average
System.out.println(getAverage());
}
private static void initializeArray(){
array = new double[5][2];
array[0][0]=1.1;
array[0][1]=12.3;
array[1][0]=3.4;
array[1][1]=5.8;
array[2][0]=9.8;
array[2][1]=5.7;
array[3][0]=4.6;
array[3][1]=7.45698;
array[4][0]=1.22;
array[4][1]=3.1478;
}
private static double getAverage(){
int counter=0;
double sum = 0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
sum = sum+array[i][j];
counter++;
}
}
return sum / counter;
}
}
double sum=0;
int size=0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
size+=arr[row].length;
}
double average = sum/size;
System.out.println("StudentAverage is: "+average);
I'm trying to create the following output:
TOTAL SALES BY REGION
Region 1: 7,845.00
Region 2: 5,636.00
Region 3: 7,879.00
Region 4: 9,174.00
From this Array:
double[][] sales = {{1540.0, 2010.0, 2450.0, 1845.0}, // Region 1 sales
{1130.0, 1168.0, 1847.0, 1491.0}, // Region 2 sales
{1580.0, 2305.0, 2710.0, 1284.0}, // Region 3 sales
{1105.0, 4102.0, 2391.0, 1576.0}}; // Region 4 sales
This is what I have so far, but it prints all the numbers from the array plus the accumulation, how do i only print the sums of each row? Also, it must be done in a normal nested for loop.
public void print(double [][] salesArray)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (int i = 0; i < salesArray.length; i++) {
double sum = 0.0;
for (int j = 0; j < salesArray[0].length; j++) {
sum += salesArray[i][j];
System.out.println(sum);
}
}
}
Try this:
public void print(double [][] salesArray)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (int i = 0; i < salesArray.length; i++) {
double sum = 0.0;
for (int j = 0; j < salesArray[0].length; j++) {
sum += salesArray[i][j];
}
System.out.println(sum);
}
}
The difference is that you're moving the printing out to the outer loop. This way, the inner loop will do the sums of a row and then when the sum is complete, the outer loop will print it.
Problem:
Write a program to calculate the wages of 5 hourly-paid employees in the company. Your program will input for each of the 5 employees the employee ID, the number of hours they worked and his/her pay rate. These data are to be stored into 3 parallel arrays: employee_ID, hours, and payrate. Your program will then call a method to calculate the wage of each employee, the results will be stored in another parallel array. Output the 4 parallel arrays side-by-side. Your program will then call 3 methods: findAve to determine the average pay of the 5 employees, findMax and findMin to determine and return the ID of the employee who receives the highest and lowest pay respectively. The results will be outputted in the main method.
Trouble with: How do I implement a method call to get an array average?
Code:
public class Employees {
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
int[] id;
id = new int[5];
int[] payrate;
payrate = new int[5];
int[] wage;
wage = new int[5];
final int EMPLOYEES = 5; // Number of employees
int[] hours = new int[EMPLOYEES]; // Array of hours
System.out.println("Enter the hours worked by " +
EMPLOYEES + " employees.");
// Get the hours for each employee.
for (int index = 0; index < EMPLOYEES; index++)
{
System.out.print("Employee " + (index + 1) + ": ");
hours[index] = keyboard.nextInt();
}
System.out.println("The hours you entered are:");
// Display the values entered.
for (int index = 0; index < EMPLOYEES; index++)
System.out.println(hours[index]);
System.out.println("Enter the payrate worked by " +
EMPLOYEES + " employees.");
// Get the payrate for each employee.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
{
System.out.print("Employee " + (index1 + 1) + ": ");
payrate[index1] = keyboard.nextInt();
}
System.out.println("The payrate you entered are:");
// Display the values entered.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
System.out.println(hours[index1]);
System.out.println("Enter the wage worked by " +
EMPLOYEES + " employees.");
// Get the wage for each employee.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
{
System.out.print("Employee " + (index2 + 1) + ": ");
wage[index2] = keyboard.nextInt();
}
System.out.println("The wage you entered are:");
// Display the values entered.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
System.out.println(wage[index2]);
}
//A method that calculates and returns the average of a passed array.
public static void calculateAverage (int[] wage)
{
int average = 0;
int total = 0;
for (int i=0; i<=wage.length; i++)
{
total += wage[i];
}
average = (total / wage.length);
return;
}
System.out.println(average);
}
You've done most of it in calculateAverage() already. But there's a couple issues.
You want to set your for loop to be i<wage.length rather than <= because arrays start at 0, so when i = length of the actual array, you'll get an out of bounds exception. ie, if there's 5 employees, wage.length == 5 where as the indexes are 0, 1, 2, 3, 4.
you're not returning anything. You've calculated the average so return it.
You'll need to set the return type other than void. I would also recommend NOT using an integer just in case your average turns out to be a decimal. You'd have to cast your int values first before calculation.
Rough fixes:
public static double calculateAverage (int[] wage) {
double average = 0;
int total = 0;
for (int i=0; i<wage.length; i++) {
total += wage[i];
}
average = (double) total / (double) wage.length;
return average;
}
Your system.out.println afterwards also can't access average since it's out of scope of the method. You can call it like this:
System.out.println(calculateAverage(wage));
Your calculateAverage method is returning void, which means it doesn't return a value. You should make it return the average.
PS: for monetary values, I suggest you to use the double instead of int. Double accept decimal values when int does not.
public static int calculateAverage (int[] wage)
{
int average = 0;
int total = 0;
for (int i=0; i<wage.length; i++)
{
total += wage[i];
}
average = (total / wage.length);
return average;
}
Using multi-dimensional arrays is a first for me, so my understanding of some of the aspects that come with these arrays are a bit...vague. Now for a quick review of what this program will be used for once completed...
It collects the inputted students names and four corresponding test scores. You can find the average of the school with it and now I'm attempting to find average of each individual student.
public class StudentGradesView extends FrameView {
int [][] aryStudent = new int [15][4]; // [15] being max students [4] being # of test scores
String[] studentNames = new String[15];
int numOfStudents = 0; //student names start from 0...
int marks = 0;
int test1;
int test2;
int test3;
int test4;
public StudentGradesView(SingleFrameApplication app) {
//unimportant...for GUI
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
//this is fine...just collects the names and test scores and ists them in studentListField...
aryStudent[numOfStudents][0] = Integer.parseInt(test1Field.getText());
aryStudent[numOfStudents][1] = Integer.parseInt(test2Field.getText());
aryStudent[numOfStudents][2] = Integer.parseInt(test3Field.getText());
aryStudent[numOfStudents][3] = Integer.parseInt(test4Field.getText());
StringBuilder sb = new StringBuilder();
for (int x=0; x <= numOfStudents && x<15; x++) {
sb.append(firstNameField.getText() + " " + lastNameField.getText());
for (int y=0; y < 4; y++) {
sb.append(" " + aryStudent[x][y]);
}
sb.append("\n");
}
studentListField.setText(sb.toString());
numOfStudents ++;
}
private void classAverageButtonActionPerformed(java.awt.event.ActionEvent evt) {
//finds school average....its fine
for(int x = 0; x < numOfStudents && x<15; x++) {
averageField.setText("The class average is " + (aryStudent[x][0] + aryStudent[x][1] + aryStudent[x][2] + aryStudent[x][3])/4 + "%");
}
}
private void studentAverageButtonActionPerformed(java.awt.event.ActionEvent evt) {
But then! This...I thought this would list the students averages individually, but it only inputs one student at a time, which is a problem...All it needs to do is list similar to this...
John Smith 78
Jane Doe 80
etc etc
for (int i = 0; i < numOfStudents; i++) {
for (int y = 0; y < marks; y++) {
averageField.setText("Student" + (aryStudent[y][0] + aryStudent[y][1] + aryStudent[y][2] + aryStudent[y][3])/4);
}
}
marks++;
}
what is exactly the variable marks in the last piece of code? it is outside the loop so it does not actually do anything. What I expect your code to do if for instance there are 4 students and marks is 3 would be the following
(i=0 y=0), StudentA
(i=0 y=1), StudentB
(i=0 y=2), StudentC
(i=1 y=0), StudentA <AVG>
(i=1 y=1), StudentB <AVG>
(i=1 y=2), StudentC <AVG>
(i=2 y=0), StudentA <AVG>
(i=2 y=1), StudentB <AVG>
(i=2 y=2), StudentC <AVG>
....
Try to print your results in text mode first (without any GUI). When it will work there you can move to GUI.
Your indices does not appear to be correct. You're using y, which is the mark index as the student index, and i is unused. Also, the way you did it, you don't need 2 loops.
This problem might've been avoided if you named i s for student and y m for mark.
Also, by using setText, you're replacing the text, not adding to it. Assuming you're using a JTextArea, you should use append instead.
It should look like:
averageField.setText(""); // clear
for (int s = 0; s < numOfStudents; s++)
averageField.append(studentNames[s] + " - " + (aryStudent[s][0] +
aryStudent[s][1] + aryStudent[s][2] + aryStudent[s][3])/4 + "\n");
A more generic way:
averageField.setText(""); // clear
for (int s = 0; s < numOfStudents; s++)
{
int average = 0;
for (int m = 0; m < marks; m++)
average += aryStudent[s][m];
average /= 4;
averageField.append(studentNames[s] + " - " + average + "\n");
}
Note that you're class average also appears to be incorrect. It currently only shows the last student's average (setText also replaces as you go).
Something like this should work:
int average = 0;
for (int s = 0; s < numOfStudents; s++)
for (int m = 0; m < marks; m++)
average += aryStudent[s][m];
average /= numOfStudents * marks;
averageField.setText("The class average is " + average + "%");
Also, wouldn't (or shouldn't) numOfStudents be limited to 15, why are you checking for both values?
I have six tasks that need to be completed but i do not know how to display them. I haave all the code to calculate each task needed but when it comes to applying them to my tester class i am stuck. below is my code for the original class. these are the task that need to be done:
Display the original data set, as shown in the table.
The average profit for the supermarket chain.
The city with the highest profit.
A list of all the cities with profit at, or above the average.
The cities and their profit listed in descending order of the profits.
Make a horizontal graph showing the performance of each supermarket
Please help because ive been doing this for the last couple days and still havent been able to do anything... i must be stupid please help
package supermarkets;
public class Supermarkets
{
private String[] city = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
private double[] profit = {10200000, 14600000, 17000000, 6000000,
21600000, 9100000, 8000000, 12500000, 2000000, 4500000};
public Supermarkets(String[] c, double[] p)
{
//array for the city
city = new String[c.length];
for (int i = 0; i < c.length; i++)
city[i] = c[i];
//array for the profits
profit = new double[p.length];
for(int i = 0; i < p.length; i++)
profit[i] = p[i];
}
//sums up the profits from the cities
public double sumArray()
{
double sum = 0;
for (int i = 0; i < profit.length; i++)
sum = sum + profit [i];
return sum;
}
//calculates the average of the profits from the cities
public double average()
{
return sumArray() / profit.length;
}
//shows highest profit
double findHighestProfit()
{
double highest = profit[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest )
highest = profit [i];
}
return highest;
}
//gives the above average profit
public String aboveAvarage()
{
String s = "";
double avg = average();
for (int i = 0; i < profit.length; i++)
if (profit [i] > avg)
s = s + city[i] + " " + profit[i] + "\n";
return s;
}
//creates a graph showing city and profits
public String makeGraph()
{
String s = "";
for (int i = 0; i < profit.length; i++)
{
s = s + city[i] + " ";
int x = (int) Math.floor( profit[i] );
for(int j = 1; j <=x; j++)
s = s + "*";
s = s + "\n";
}
return s;
}
//resets profits position from least to greatest
public int findPosition(int startScanFrom)
{
int position = startScanFrom;
for (int i = startScanFrom + 1; i < profit.length; i++)
if (profit[i] < profit[position])
position = i;
return position;
}
//swaps values for city and profits
public void swap(int i, int j)
{
// Swap the profits
double temp = profit[i];
profit[i] = profit[j];
profit[j] = temp;
// Swap the cities
String str = city[i];
city[i] = city[j];
city[j] = str;
}
}
You didn't provide your test/driver program, so I had to make a lot of assumptions.
Just write a method that loops through the two arrays and prints the values.
Your method to find the average profit looks fine.
You have a method to find the highest profit, but you need to display the city. I added a method to find the city with the highest profit.
//shows city with highest profit
String findHighestProfitCity()
{
double highest = profit[0];
String c = city[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest ) {
highest = profit [i];
c = city[i];
}
}
return c;
}
This is a fairly straightforward method. Once you calculate the average, just loop through the city/profit arrays and display any cities that have a profit higher than the average.
The easiest way to do this with the data organized in two arrays would be to write a custom sort routine that sorts the profit array and makes a swap in the city array each time one is necessary in profit.
The test data you put in your city and profit arrays is way too big to display graphically. Your makeGraph() method tries to draws x asterisks for each value in profit. Even after cutting five zeroes off of each value, that still didn't fit on my screen, so I modifed that method to only draw x/10 asterisks for each profit
for(int j = 1; j <= x/10; j++)
s = s + "*";
Here's a test/driver program that you can use as a starting point.
package supermarkets;
public class SupermarketDriver {
/**
* #param args
*/
public static void main(String[] args) {
String[] cities = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
double[] profits = {102, 146, 170, 60, 216, 91, 80, 125, 20, 45};
Supermarkets sm = new Supermarkets(cities, profits);
System.out.println(sm.makeGraph());
System.out.println("Average profit: " + sm.average());
System.out.println();
System.out.println("Highest profit city: " + sm.findHighestProfitCity() + ", " + sm.findHighestProfit());
}
}