Adding values on 2d array java - java

I have created a program that lets the user input the number of rows and columns they want in a 2d array and then it fills the array with all even numbers starting from 0.
I have to add all the numbers in the array to get a total sum and I have no idea how to do that. The rest of my program is complete I'm just having trouble with the sum.
Here is my code:
import java.util.*;
public class ArrayOver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many rows? ");
int x = scan.nextInt();
System.out.println("How many columns? ");
int y = scan.nextInt();
int[][] nums = new int[x][y];
fillArray(nums);
displayArray(nums);
System.out.println();
}
public static void fillArray(int nums[][]) {
int count = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length ; col++) {
nums[row][col] = count;
count++;
count++;
}
}
}
public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {
System.out.println(Arrays.toString(nums[row]));
}
}
}

Try this:
public static void countArray(int[][] nums)
{
int total=0;
for (int row=0;row<nums.length;row++)
for (int col=0;col<nums[0].length;col++)
total += nums[row][col];
System.out.println(total);
}
This should go through all the numbers in the array and add their values to total.

If you want sum all elements of array, just do it:
int sum = 0;
for(int row = 0; row < nums.length ; row++) {
for (int col = 0; col < nums[row].length ; col++) {
sum = sum + nums[row][col];
}
}

Related

How to write a method for a transposed matrix?

I am trying to create an application class MatrixApplication, in which the user first enters the number of rows and columns of the matrix.
This will be used to create an array object.
Then the elements of the Matrix are called up row by row and column by column. When all elements have been read in, they are assigned to the matrix object.
Next, the array is transposed and finally the transposed array is displayed.
How do I assign the elements to the Matrix object?
How do I display a transposed array?
package domain;
public class Matrix {
private int[][] numbers;
public Matrix(int rows, int columns) {
setNumbers(numbers);
if (rows < 1)
rows = 1;
else
rows = rows;
if (columns < 1)
columns = 1;
else
columns = columns;
numbers = new int[rows][columns];
}
public final void setNumbers(int[][] numbers) {
this.numbers = numbers;
}
public int[][] getNumbers() {
return numbers;
}
public int[][] transpose() {
int[][] transpose = new int[numbers[0].length][numbers.length];
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < numbers[0].length; ++j) {
transpose[j][i] = numbers[i][j];
}
}
return transpose;
}
}
package ui;
import java.util.Scanner;
import domain.Matrix;
public class MatrixApplication {
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows of the matrix:");
int rows = input.nextInt();
System.out.print("nter the number of columns of the matrix:");
int colums = input.nextInt();
Matrix matrix = new Matrix(rows, colums);
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
}
System.out.printf("The transposed matrix: %d",matrix.transpose());
}
}
And if I want this form of transposed matrix:
example of a 4x2 array to a 2x4 array
Simply read the numbers into a two-dimensional array and call matrix.setNumbers.
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
matrix.setNumbers(numbers);
System.out.printf("The transposed matrix: %s", Arrays.deepToString(matrix.transpose()));

Need to print the max element column in java

Hello I am new in java and I want to write a program where I will print the max element from the column in 2D table. I am updating a picture to show what actually I want to print.
Here is the code:
import java.util.*;
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
int[][] table = new int [col][row];
int max= 0;
for(int i=0; i<col; i++){
for(int j=0; j<row; j++){
max= table[i][0];
table[i][j]= sc.nextInt();
if(max<table[i][j]){
max= table[i][j];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
}
}
You can index a matrix (2D table) like this:
matrix[row][column]
where row and column are 0-based indexes.
You have to change the loop like this:
int max= 0;
for(int i=0; i<col; i++){
// select first element of a column as temp max
max= table[0][i];
for(int j=0; j<row; j++){
// cycle on rows
if(max<table[j][i]){
max= table[j][i];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
You have to cycle on column. Select the first element of a column as temporary maximum
You have to init the max when you end a row, not inside the nested loop
Side note: I suggest you to keep the code clean (because is a simple example and I assume you have a little file) and separate tasks:
First, read the file (perhaps print the file content to be sure the content it's ok)
Then, check the maximum of each column
In this way will be simpler for you to catch problems.
You need to separate the values insertion and finding the maximum value so you can iterate the array by columns
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
table[i][j] = sc.nextInt();
}
}
int[][] table = new int[col][row];
for (int i = 0; i < col; i++) {
int max = table[0][i];
for (int j = 0; j < row; j++) {
if (max < table[j][i]) {
max = table[j][i];
}
}
System.out.println("Maximum number is " + max);
System.out.println();
}
}
}
Output
Maximum number is 10
Maximum number is 5
Maximum number is -3
Maximum number is 9

Trying to get the average for each element in a two dimensional array

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);

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Why aren't the "println" messages printing?

I have written this program to create a list, then use the list to populate an array. The method magicCheck then checks to see if the matrix is a magic square. I initially wrote it to be a defined matrix of size 4x4. When I did that, everything worked fine. Now I want to let the user decide the size of the array (nxn). After adding the code to prompt the user for n, and creating the matrix based on nxn rather than 4x4, my printMatrix method has stopped working.
When I run the program as is, and enter n=2, first=2, diff=2, this is the output I get:
"Enter size of array (in form nxn), n:
4
Enter first and diff :
2
2
It is not a magic square."
Can anyone tell me why printMatrix is no longer working? Also, I know that my magicCheck method is sloppy with the loops and I'm sure there are better ways to handle it, but I'm still very new and piecing it together any way I can to get it to work. Please be gentle :]
Here is my code:
import java.util.*;
public class MagicSquare
{
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
static Scanner console = new Scanner (System.in);
public static void createArithmeticSeq(int [] list)
{
//prompt user for array size
System.out.println("Enter size of array (in form nxn), n:");
n = console.nextInt();
int first;
int diff;
//prompt user for first and diff
System.out.println("Enter first and diff : ");
first = console.nextInt();
diff = console.nextInt();
//process to create list of 16 elements
for (int i=0; i<listSize; i++)
{
list[i]=first+i*diff;
}
}
public static void matricize (int [] list, int [][] matrix)
{
int i = 0;
//loop through each row
for (row=0; row<matrix.length; row++)
{
//loop through each column
for (col=0; col<matrix[row].length; col++)
{
//populate matrix with values from list
matrix[row][col] = list[i++];
}
}
}
public static void printMatrix(int [][] matrix)
{
for (row=0; row < matrix.length; row++)
{
for (col=0; col < matrix[row].length; col++)
System.out.printf("%2d" + " ", matrix[row][col]);
System.out.println("\n");
}
}
public static void reverseDiagonal(int [] [] matrix)
{
int temp;
for (row=0; row<matrix.length / 2; row++)
{
temp = matrix[row][row];
matrix[row][row] =
matrix[matrix.length - 1 - row] [matrix.length - 1 - row];
matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
}
for (row=0; row<matrix.length / 2; row++)
{
temp = matrix[row][matrix.length - 1 - row];
matrix[row][matrix.length - 1 - row] =
matrix[matrix.length - 1 - row][row];
matrix[matrix.length - 1 - row][row] = temp;
}
}
public static void magicCheck(int [] list, int [] [] matrix)
{
int sum=0, sumRow=0, sumCol=0, sumDiag1=0, sumDiag2=0, magicNumber=0;
for(int i=0; i<listSize; i++)
{
sum += list[i];
magicNumber = sum /= 4;
for(row=0; row<matrix.length; row++)
{
//sum each row, then compare to magicNumber
for(col=0; col<matrix[row].length; col++)
sumRow = sumRow + matrix[row][col];
while (sumRow == magicNumber)
{
for(col=0; col<matrix.length; col++)
{
for(row=0; row<matrix[col].length; row++)
{
sumCol = sumCol + matrix[row][col];
while (sumCol == magicNumber)
{
sumDiag1 = matrix[0][0]+matrix[1][1]+matrix[2][2]+matrix[3][3];
while (sumDiag1 == magicNumber)
{
sumDiag2 = matrix[3][0]+matrix[2][1]+matrix[1][2]
+matrix[0][3];
while(sumDiag2 == magicNumber)
System.out.println("It is a magic square.");
}
}
}
}
}
}
}
System.out.println("It is not a magic square.");
}
public static void main (String [] args)
{
int [] list = new int [listSize];
int [] [] matrix = new int [rows] [columns];
createArithmeticSeq (list);
matricize(list, matrix);
printMatrix(matrix);
System.out.print("\n");
reverseDiagonal(matrix);
printMatrix(matrix);
magicCheck(list, matrix);
}
}
You declare:
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
before n is set according to the user-input.
First, remove the final from the declarations.
Second, after you read:
n = console.nextInt();
Do:
rows = n;
columns = n;
...
And last, in your main method, switch the order of the lines:
int [] [] matrix = new int [rows] [columns];
createArithmeticSeq (list);

Categories

Resources