Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having a hard time outputting the the average of each row in this array that I'm trying to run:
int x, y, val;
double sum=0, ave, sumtot;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
}
sumtot = sum;
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Hope you guys can help me with this.:)
You might want to try out is something like this (with slightly cleaned up code). If you need to store the data for averages of each row rather than just printing them on fly, you could add them into an array or arraylist.
double sum=0, ave;
int x = khel.nextInt();
int y = khel.nextInt(); // input for array sizes
int val = x * y;
double rowSum; // something to contain data
double[][] myArray = new double[x][y];
for(int i=0; i < myArray.length; i++)
{
for(int j=0; j < myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble(); // input for array content
}
}
for(int i=0; i < myArray.length; i++)
{
rowSum = 0; // reset value each row
for(int j=0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + "\t");
sum += myArray[i][j];
rowSum += myArray[i][j]; // add value from array
}
System.out.println(rowSum / (double)myArray[i].length); // print average from each row
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
// this is the average of the whole table
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Review the logic of this and apply it in your code (assume that array[5][5] already has values)...
for( int row = 0; row < 5; row++ )
{
int rowSum = 0;
for( int column = 0; column < 5; column++ )
{
rowSum += array[row][column];
}
System.out.println( String.format( "Sum of values in row %d: %d", row, rowSum ) );
System.out.println( String.format( "Average of values in row %d: %d\n", row, ( rowSum / 5 ) ) );
}
If you just want to output the average per row, editing from what you current have. You can do this:
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
rowSum += myArray[i][j]; //Calculate sum of each row
}
System.out.println("Avg for row " + (i+1) + ":" + rowSum/(double)myArray.length);
rowSum = 0; //reset value for calculation for next row
}
Take note of where I placed the println() statement. Placing it after the inner loop will ensure it prints after all column values are added in each row.
I finally got it! Thank you for all your output guys!:) It drew closer to getting it right.:) Here's how I did it:
int x, y, val, i, j, row=1;
double sum=0, ave, rowSum;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(i=0; i<myArray.length; i++)
{
for(j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(i=0; i<myArray.length; i++)
{
rowSum = 0;
for(j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
rowSum = rowSum + myArray[i][j];
}
rowSum = rowSum / myArray[i].length;
System.out.println("");
System.out.println("The average of the row " + row + " is " + rowSum + ".");
row++;
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
}
}
Your inputs helped me a lot. Thanks a bunch.:)
Related
I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output:
The problem is every time the maximum sum is the third row how to solve these issues.
int [][] scores = new int[4][3];
for (int i=0; i<scores.length; i++)
{
System.out.print("Enter values for row "+i+": ");
for (int j=0; j<scores[i].length;j++)
scores[i][j] = kbd.nextInt();
}
int sum, sumMax, ii=0;
for (int i=0; i<scores.length; i++)
{
sum =0; sumMax = 0; ii=0;
for (int j=0; j<scores[i].length;j++)
{
sum += scores[i][j];
if (sum>sumMax)
{
sumMax = sum;
ii = i;
}
}
}
System.out.println("Row "+ii+" has the maximum sum");
System.out.print("Row "+ii+" has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
To print a specific row, you need one loop only
System.out.print("Row " + ii + " has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
Or with Arrays.toString
System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row
int sum, sumMax = Integer.MIN_VALUE, ii = 0;
for (int i = 0; i < scores.length; i++) {
sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
if (sum > sumMax) {
sumMax = sum;
ii = i;
}
}
You can add the rows while getting the input from scanner and store them in an array. Then you can search for the max value in the sums array:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int[][] scores = new int[4][3];
int[] rowSums = new int[4];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter values for row " + i + ": ");
for (int j = 0; j < scores[i].length; j++){
scores[i][j] = kbd.nextInt();
rowSums[i] += scores[i][j];
}
}
int index = 0;
int maxSum = rowSums[index];
for(int i = 1; i < rowSums.length; i++){
if(rowSums[i] > maxSum){
maxSum = rowSums[i];
index = i;
}
}
System.out.println("Row "+index+" has the maximum sum");
System.out.print("Row "+index+" has the following values: ");
for(int i = 0; i < scores[index].length; i++){
System.out.print(scores[index][i] + " ");
}
}
}
I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}
I'm getting an error on line 66 c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];. I went through the indices by hand, just can't figure out where the index went wrong. Help is greatly appreciated.
package arrayproducts;
import javax.swing.JOptionPane;
public class ArrayProducts {
public static void main(String[] args) {
String output = "";
int rowA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixA."));
int colA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixA."));
int rowB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixB."));
int colB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixB."));
if( colA != rowB){
output += "Cannot perform matrix operation: Inner matrix dimensions must agree.";
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
output += "\nMatrixB has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
return;
} else {
output += "\nDot Product Begin:";
int [][] a = new int[rowA][colA];
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
int [][] b = new int[rowB][colB];
output += "\nMatrixA has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
int [][] c = new int[rowA][colB];
////
// enter first matrix
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colA; j++){
a[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixA, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add first matrix to output
output += "\nThe first matrix is: \n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colA; j++){
output += " " + a[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// enter second matrix
for(int i = 0; i < rowB; i++){
for(int j = 0; j < colB; j++){
b[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixB, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add second matrix to output
output += "\nThe second matrix is: \n";
for(int i=0; i < rowB; i++){
for(int j=0; j < colB; j++){
output += " " + b[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// compute the product
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colB; j++){
for(int k = 0; k < colA ; k++){ // either colA or rowB will work here
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];
}
}
}
output += "\nThe product of MatrixA and MatriB is:\n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colB; j++){
output += " " + c[rowA][colB];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
}
I guess you meant to use the indices i,j,k instead of rowA, colB etc in the following code.
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];
I will show you a simple example.
int[] a = new int[3];
That mean a can have only 3 values.
a[0], a[1] and a[2]
If you try a[3] it will be out of bound.
So. You have
int [][] c = new int[rowA][colB];
And try to access c[rowA][colB] which is out of bound.
In your three for loops, I think, you want to use i,j and k.
package SinemaSalonu;
public class SinemaSalonu {
public static void main(String args[]) {
int[][] matrix = new int[10][20];
for (int k = 0; k < 10; k++) {
matrix[k][0] = k + 1;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(" " + matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\n\n" + " " + "P E R D E");
}
}
when i run this code the resulting matrix' last row is not centered with others cause of the number "10" in the last row. it caused the row to slightly shift to the right. i want to fix this and center each row.
In order to align the lines with a single digit with the lines that start with two digit replace your printing:
System.out.print(" " + matrix[i][j] + " ");
with:
int n = matrix[i][j];
System.out.print(" " + (n < 10 ? " " + n : n) );
It will add an extra space before each line that starts with a single digit.
It will look like this:
i have a 2D array 3X5 and i need the to multiply each element in column one, and so forth. This is what ive attempted without any luck. the result is not correct. i tried storing each column into an array and multiply each element from that array but i get the same results.
edit: yes i am aware there is no multiplication in this code, that is because it yields an incorrect product.
for(int j = 0; j < 5; j++){
double v = 0.0;
double[] ex = new double[3];
double volumeBox1 = 0.0;
for(int i = 0; i < 3; i++){
v = d[i][j];
System.out.println(v);
for(int z = 0; z < 3; z++){
ex[z] = v;
}
}
System.out.println("The volume of box " + (j+1) + " is: " + volumeBox1);
I will assume your matrix is 5 x 3, which is more logical and convenient than 3 x 5 for this use case :
for (int i = 0 ; i < d.length ; j++) {
double vol = 1;
for (int j = 0 ; j < d[i].length ; j++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}
This can of course be done with a 3 x 5 matrix but I think it makes less sense to iterate on the columns :
for (int j = 0 ; j < d[0].length ; j++) {
double vol = 1;
for (int i = 0 ; i < d.length ; i++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}