How to calculate the average of each row and column in array - java

So yesterday I asked for help, and a lot of people helped me out with my question, I really appreciated that guys. However, I run into a second problem of my homework, and I have been trying to solve it from this morning, and now it's like almost 2AM in the morning, and I'm not gonna sleep until I solve this problem. I'm not going to lie, so this is my homework to test the basic knowledge of mine. I know I make major mistakes somewhere, so please help me to point them out, so I can fix them. Thank you
The output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
aver=2.5, 3.5, 4.5
This is my current code:
import java.util.Scanner;
public class Ex {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
double averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
double averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows");
int r = sc.nextInt();
System.out.println("Enter number of columns");
int c = sc.nextInt();
System.out.println("Enter values");
int[][] matrix = new int[r][c];
for (int i = 0; i < r; i++)
{
float rowSum = 0f;
for (int j = 0; j < c; j++)
{
matrix[i][j] = sc.nextInt();
rowSum += matrix[i][j];
}
System.out.println("Average of row " + i + " " + rowSum / c);
}
for (int i = 0; i < c; i++)
{
float columnSum = 0f;
for (int j = 0; j < r; j++)
{
columnSum += matrix[j][i];
}
System.out.println("Average of column " + i + " " + columnSum / r);
}
sc.close();
}
You can find the each row sum while reading the data. For column average run loop again. Hope you will sleep :)

You can print without calling other function.
import java.util.Scanner;
public class test8 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
int rowSum = 0;
int colSumArr[] = new int[columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
rowSum = rowSum + array[i][j];
colSumArr[j] = colSumArr[j] + array[i][j];
System.out.print(array[i][j] + " , ");
}
System.out.println( " ave=" + (double)rowSum/columns);
rowSum = 0;
}
System.out.printf("aver=");
for(int i=0;i<columns;i++){
if(i!=columns -1)
System.out.print((double)colSumArr[i]/rows + ", ");
else
System.out.print((double)colSumArr[i]/rows);
}
}
}

Related

How to get the sum for each row?

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] + " ");
}
}
}

Having trouble searching array

So I have everything working fine up until the point in which I need to search. I'm really new to this so my code is probably awful I'm sorry in advance. Anyway, its a user input array, and the user should be able to search for a number in an array. Im getting the error for a duplicate variable on line 50 (int i, get 1).
import java.util.Scanner;
class SearchingSorting {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("How many numbers would you like to input?");
int num = input.nextInt();
double[] array = new double[num];
for (int i = 0; i < num; i++) {
System.out.println ("Input number " + (1 + i) + ":");
array[i] = input.nextDouble();
}
for (double temp1 : array){
System.out.print (temp1 + "\t");
}
input.close();
int pass;
int i;
int hold;
for(pass = 1; pass < array.length; pass++)
{
for(i = 0; i < array.length - 1; i++)
{
if(array[i] > array[i+1])
{
hold = (int) array[i];
array[i] = array[i+1];
array[i+1] = hold;
}
}
System.out.println("\nSorted number is: ");
for(i = 0; i < array.length; i++)
System.out.print(" " + array[i]);
}
int i, get1;
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
for(i = 0; i < numbers.length; i++)
{
numbers[i] = i * 10;
}
System.out.print("Enter search number: ");
get1 = keyboard.nextInt();
SearchMethod(numbers, get1);
}
public static void SearchMethod(int[] num, int get2)
{
int i ;
boolean j = false;
for(i = 0; i < num.length; i++)
{
if(num[i] == get2)
{
j = true;
break;
}
}
if(j == true)
System.out.println(get2 + " is found at num[" + i + "]");
else
System.out.println(get2 + " is not found in an array");
}
}
You are trying to declare a new variable with the same name ("i") in the same scope.
Rename your variable i on line 50.

Creating a matrix from a text file - Java

I have this text file:
2
2
12
13
23
24
49
59
69
79
the first two numbers should be the rows and columns of the matrix, which is 2x2 in this case. My issue that I'm trying to get around is finding a way to include a second 2D array that holds the second matrix.
my code:
Scanner fileInput = new Scanner(new File("input1.txt"));
int n1 = fileInput.nextInt();
int n2 = fileInput.nextInt();
System.out.print("matrix is " + n1 + "x" + n2 +"\n");
int [][] firstMatrix = new int [n1][n2];
int [][] secondMatrix = new int [n1][n2];
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
firstMatrix[i][j] = fileInput.nextInt();
}
}
}
System.out.println("Matrices: ");
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.println(firstMatrix[i][j]);
}
}
it only prints the following:
12
13
23
24
How do I make it read the next four lines of integers from the file? It would also be helpful to understand how I can make it look something like this:
12 13
23 24
EDIT: This approach seemed to help with the last question:
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
{
System.out.print(firstMatrix[i][j] + " " );
//System.out.print(secondMatrix[i][j] + " ");
}
System.out.println();
}
The only problem I'm facing now is being able to include the four other integers and turn them into a matrix.
You can group them to 1 array:
int matrixNumb = 2; // number of matrix
int [][][] matrix = new int [matrixNumb][n1][n2];
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
matrix [h][i][j] = fileInput.nextInt(); // read from file
}
}
}
}
System.out.println("Matrices: ");
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.print(matrix[h][i][j]);
System.out.print("\t"); //How do you want to separate columns?
}
System.out.print("\r\n"); //How do you want to separate rows?
}
System.out.println(); //How do u want to print next matrix?
}
I have not compiled or run it, but hope it help.
You can just read data for the two arrays from file sequentially, like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
private static void readMatrix(final Scanner scanner, final int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
}
}
}
}
private static void displayMatrix(final int[][] matrix) {
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();
}
}
public static void main(final String... args) throws FileNotFoundException {
final Scanner scanner = new Scanner(new File("input.txt"));
final int n1 = scanner.nextInt();
final int n2 = scanner.nextInt();
System.out.print(String.format("The matrix is %d x %d \n", n1, n2));
final int[][] firstMatrix = new int[n1][n2];
final int[][] secondMatrix = new int[n1][n2];
System.out.println("Reading data to first matrix");
readMatrix(scanner, firstMatrix);
System.out.println("Reading data to second matrix");
readMatrix(scanner, secondMatrix);
System.out.println("First Matrix");
displayMatrix(firstMatrix);
System.out.println("Second Matrix");
displayMatrix(secondMatrix);
}
}
for(int i = 0; i < n1*n1; i++)
{
for(int j = 0; j < n2*n2; j++)
{
if(fileInput.hasNextInt())
{
if(i < n1){
firstMatrix[i][j] = fileInput.nextInt();
}
else
{
secondMatrix[i][j] = fileInput.nextInt();
}
}
}
}
You have two matrix of size n*n so you can do like this:

How do i output random numbers for 2 different arrays?

This is what i have so far but the output for both arrays is the same randomly generated numbers instead of different ones for each array.
import java.util.Scanner;
public class Prog2_b {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Program #2b, Breanna Bergado, mascID 1885");
System.out.println("Please enter number of elements for a 1D array:");
int userVal = scnr.nextInt();
//System.out.println(((Object)userVal).getClass().getName();
double[] array = new double[userVal];
double [] array2 = new double[userVal];
double dotProd = 0;
for(int i = 0; i < userVal; i++) {
array[i] = Math.random();
array2[i] = Math.random();
}
for (int j = 0; j < 2; j++){
System.out.println("a"+(j+1)+"[]");
System.out.println("----------------");
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
for(int i = 0; i < userVal; i++) {
dotProd = dotProd + array[i]* array2[i];
}
System.out.println("Dot Product is " + dotProd);
}
}
You should update your printing logic to:
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
for (int j = 0; j < userVal; j++) {
System.out.println(array2[j] + " ");
}
Your current logic just prints the first array twice. You could also use nested arrays as one of the comments suggested, but the above code will work with what you have so far.

Cannot get the addition to output [closed]

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 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Categories

Resources