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.
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 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);
}
Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;
I have to write a JAVA program where a user set the number of columns and rows of a 2d array. Then he should choose a minimum and a maximum. After that, the array is filled randomly.
I writed this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class array2d
{
public static void main (String[] args) throws java.lang.Exception
{
int rows, col, min, max;
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter number of rows and columns:");
rows = scan1.nextInt();
col = scan1.nextInt();
int[][] a = new int[rows][col];
System.out.println("Enter min and max:");
min = scan1.nextInt();
max = scan1.nextInt();
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
a[i][j] = min - (int)Math.random()*(max-min+1);
}
}
//Display on the screen
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
System.out.print(a[i][j]+ " ");
}
}
...
}
}
Then we should run a program to see if the first number of each row is a divisor of all the row:
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<col; j++)
{
if(a[i][0]%a[i][j]==0)
{
System.out.println(a[i][j]);
}
else
System.out.println("None");
}
}
That's working properly, but the generated array on my computer is displayed like that (CMD output):
And as you see in the picture, all randomly filled random are equal to the minimum specified.
So how can I display this array as like matrix and why the random numbers are showing like this.
Math#random return a number between 0.0-1.0, but less then 1.0. This does in fact make your calculation look like the following min-0, since you are parsing it as int. Due to this you are allways saying 0*(max-min+1).
In order to achive what you want you need to add braces and add to min.
For your representation problem, add a System.out.println after you finished the inner loop.
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++) {
a[i][j] = min + (int)(Math.random()*(max-min+1)); // You need brackets and add it to min
}
}
//Display on the screen
for(int i = 0; i<rows; i++) {
for(int j = 0; j<col; j++){
System.out.print(a[i][j]+ " ");
}
System.out.println(); // You need a linebreak
}
All slots of your array get filled wit the 10 value in your example, min in general :
a[i][j] = min - (int)Math.random()*(max-min+1);
yields
a[i][j] = 10 - (int)Math.random()*(10);
Math.random() returns a double greater than or equal to 0.0 and less than 1.0 , so rounded to an int, it is 0 .
so
a[i][j] = 10 - (0*(10)); // this yields 10, the value of "min"
Where you have:
a[i][j] = min - (int)Math.random()*(max-min+1);
You actually mean:
a[i][j] = min + (int) (Math.random()*(max-min+1));
The first one casts Math.random() to an int (giving zero), then multiplies it by (max-min+1) (giving zero), then subtracts it from min (giving min).
The second one multiples Math.random() by an int (giving a random double in the range [0,max-min+1) ), then casts it to an int (giving a random int in the range [0,max-min] ), and then adds min (giving a random int in the range [min,max] ).
The Idea is to create a method that is static that will calculate the average salary for a partially-filled array. Assume that numEmployees holds the number of elements in the array that have valid data. numEmployees is passed to the method.
public static double getAverage(double[ ] numEmployees)
{
double total = 0;
double average;
for (int i = 0; i < numEmployees.length; i++)
total += numEmployees[i];
average = total / numEmployees.length;
return average;
}
Do I need to add a part in the method that counts the array that are filled?
like:
int count=0;
int p=0;
if (numEmployees[p]>0)
{
count++;
p++;
}
or should I add a part in my for loop inside the message and change my total to this:
for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
total += numEmployees[i];
Than farther down
average = total / i;
public static double getAverage(double[] numEmployees)
{
double total = 0;
double count = 0;
for (int i = 0; i < numEmployees.length; i++)
if (numEmployees[i] > 0) {
total += numEmployees[i];
count++;
}
return total / count;
}
Note that if there can be no more values after the first 0, it's also good to end the loop when one is detected. What i wrote here looks for any value greater than 0, no matter where the 0's occur.