I want to write code which will add only diagonal elements.
import java.util.Scanner;
public class SabMat {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double [][] matrix = new double [4][4];
System.out.print("Enter matrix elements by row");
for (int i=0; i < matrix.length; i++) {
matrix[i][0] = input.nextDouble();
matrix[i][1] = input.nextDouble();
matrix[i][2] = input.nextDouble();
matrix[i][3] = input.nextDouble();
}
int total=0;
for (int row=0; row < matrix.length; row++) {
for (int column=0; column < matrix[row].length; column++) {
if (row == column){
total += total + matrix[row][column];
} else if (row!=column){
total = 0;
}
}
}
System.out.println("The sum of elements in the major diagonal is"+total);
}
}
The result is not good!
The problem is only (3,3) element is added to total not the previous three.
How to solve this?
Your code does not work because it resets the total every time you're off the main diagonal.
Note that you do not need two loops if all you want is to total the elements of the diagonal: rather than running two nested loops and waiting for row == column, run a single loop, and total up the values of matrix[i][i].
for (int i = 0 ; i != matrix.length ; i++) {
total += matrix[i][i];
}
Related
Trying to change this code so I can get user input instead of a predefined array. Can anyone help? This code needs to have the method sum with the double[][] parameter. The method should return the sum of the elements of the array passed to it and should be rectangular.
import java.util.Scanner;
class Array2_1
{
public static double sum (double[][] array)
{
double sum = 0;
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[0].length; j++)
{
sum += array[i][j];
}
}
return sum;
}
public static void main(String[] args)
{
System.out.println("")
double a [][] = {
{1.2, 2},
{6, 7.2},
{11, 12}
};
System.out.println(sum(a));
}
}
You can use Scanner to read values from the keyboard. First, read the values for the dimensions of the array and then input values for the individual indices using nested loops.
You can also define a method to display the array in the tabular form.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
double array[][] = new double[rows][cols];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("Enter value for array[%d][%d]: ", i, j);
array[i][j] = scanner.nextDouble();
}
}
System.out.println("The array:");
print(array);
System.out.println("Sum of elements: " + sum(array));
}
public static double sum(double[][] array) {
double sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
}
return sum;
}
public static void print(double[][] array) {
for (double[] row : array) {
for (double col : row) {
System.out.print(col + "\t\t");
}
System.out.println();
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 2
Enter value for array[0][0]: 1.2
Enter value for array[0][1]: 2
Enter value for array[1][0]: 6
Enter value for array[1][1]: 7.2
Enter value for array[2][0]: 11
Enter value for array[2][1]: 12
The array:
1.2 2.0
6.0 7.2
11.0 12.0
Sum of elements: 39.4
I have added comments to the code for your understanding. Hope it answers your query.
public static void main(String[] args) {
//You can use the Scanner class for taking input
Scanner scan = new Scanner(System.in);
//take input for the number of rows in array
System.out.println("Enter no. of rows in array");
int row = scan.nextInt();
//take input for the number of columns in array
System.out.println("Enter no. of columns in array");
int col = scan.nextInt();
//create an array with row and col as dimensions of the 2D array
double[][] arr = new double[row][col];
//this for loop is for inputting elements in your array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
arr[i][j] = scan.nextInt();
//this for loop is for printing out the elements
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
scan.close();
//now give a call to your sum() method and print the result
System.out.println(sum(arr));
}
In this program, I have to fill a 2D array with user-inputted values and find the average of all the array's elements. However, the program instead finds the average by dividing the sum by the number of rows instead of the number of numbers. I tried setting average to a 2D array in itself but it only recognized one reference instead of both of them. Halp
public static void main(String[] args) {
int[][] array = createArray();
System.out.printf("The average of this array is " + "%.2f", average(array));
}
public static int[][] createArray() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = sc.nextInt();
System.out.print("Enter the number of columns: ");
int numColumns = sc.nextInt();
int[][] array = new int[numRows][numColumns];
System.out.println("Enter " + array.length + " rows and " + array[0].length + " columns");
for (int row = 0; row < array.length; row++)
for (int column = 0; column < array[0].length; column++)
array[row][column] = sc.nextInt();
return array;
}
public static double average(int[][] a) {
int sum = 0;
double average = 0;
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
average = sum / a.length;
}
return average;
}
}
The problem is here:
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
average = sum / a.length;
}
The issue is that you are re-assigning average on every iteration through the loop. Instead, you should calculate it after all of the loops are done:
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
}
average = (double) sum / (a.length * a[0].length);
The product (a.length * a[0].length) will give you the size of all of the arrays in the array. You add the cast to (double) in the calculation of the average to avoid integer arithmetic problems (e.g., 25/6 is 4).
Note that if the arrays are large enough, it is possible for sum to overflow.
I'm building out a user defined array as a game board. The characters used "O" and "." have to be randomized and the "O" has to appear more than once.
This is what I have thus far.
import java.util.Scanner;
public class PacMan {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
boolean[][] cookies = new boolean[row+2][column+2];
for (int i = 1; i <= row; i++)
for (int j = 1; j <= column; j++);
cookies [row][column] = (Math.random() < 100);
// print game
for (int i = 1; i <= row; i++)
{
for (int j = 1; j <= column; j++)
if (cookies[i][j]) System.out.print(" O ");
else System.out.print(". ");
System.out.println();
}
}
}
The output, for example, produces a 5 x 5 grid, but the "O" only appears once and is at the bottom right of the grid.
Assistance randomizing the "O" and "." and having the "O" appear in random fashion throughout the board which is initialized by the user input via Scanner.
Here is the updated code which is producing the output that I'm looking for and is user defined.
import java.util.*;
public class PacManTest
{
public static void main(String[] args)
{
char O;
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
char board[][] = new char[row][column];
for(int x = 0; x < board.length; x++)
{
for(int i = 0; i < board.length; i++)
{
double random = Math.random();
if(random >.01 && random <=.10)
{
board[x][i] = 'O';
}
else {
board[x][i] = '.';
}
System.out.print(board[x][i] + " ");
}
System.out.println("");
}
}
}
The main issue is the typo in the first loop:
cookies [row][column] = (Math.random() < 100);
should be
cookies [i][j] = (Math.random() < 100);
Second, Math.random() returns a value greater than or equal to 0.0 and less than 1.0 (doc). So, (Math.random() < 100); will always be true. If you want a 50% chance of an O or . use:
cookies[i][j] = Math.random() < 0.5;
Also, not sure what your motivation is for using a starting index of 1 but array indexes start at 0.
import java.util.*;
public class triangle{
public static void main(String args[]){
Scanner input_Obj = new Scanner(System.in);
System.out.println("Enter the number of lines in the triangle");
int sum = 0;
int mat_size = input_Obj.nextInt(); //input of the size of the triangle
System.out.println("enter the inputs");
int input_Array[][] = new int[mat_size][mat_size];
for (int row = 0; row < mat_size; row++){
for (int col = 0; col < col; col++){
input_Array[row][col] = input_Obj.nextInt();
}
}
if (mat_size >= 3){
int[] sum_array = new int[2*(mat_size-2)];
for (int row = 1; row < mat_size; row++){
for(int col = 0;col<=row;col++){
sum += input_Array[row][col];
}
sum_array[row-1] = sum;
}
}
else if(mat_size == 2){
if (input_Array[1][0]<input_Array[1][1]){
System.out.println("minimum of the two elements in second line is:" +input_Array[1][0]);
}
else{
System.out.println("minimum of the two elements in second line is:" +input_Array[1][1]);
}
}
else{
System.out.println("minimum sum can't be calculated");
}
}
}
It is not storing values in the input array
It is taking the input in mat_size but not taking inputs into the array
I'm trying to find the minimum sum inside the triangle
for (int col = 0; col < col; col++)
col < col this is the issue as condition is never satisfied that is why it is not taking any input, change this condition to
for (int col = 0; col < mat_size; col++)
Except for an extra column produced by the code, everything works fine except my avg method which was meant to average the value in each row. I'm new to coding, so maybe I'm not seeing the problem, but the method isn't working as intended. At first I thought it was an issue with the sum but changing it didn't really resolve the initial problem. A column input of (2,1,3) will produce an exception error at 1 but does not occur when the input is (1,3,2). Also the avg is producing only 2 regardless of column length.
I'm aiming for the code to print this when column input of (1,2,3) is entered:
A:2.0 [1.0]
B:2.0 2.0 [2.0]
C:2.0 2.0 2.0 [3.0]
where the bracketed term is the average for that row.
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 0; row < figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
public static double avg(double temp[][]) {
int sum = 0;
int avg = 0;
for (int row = 0; row < temp.length; row++){
for (int col = 0; col < temp[col].length; col++)
sum += temp[row][col];
}
avg = sum / temp.length;
return avg;
}
}
I think what you are doing wrong is instead of summing up all elements of a row and taking average, you are summing up the whole matrix and taking average which will always be the same value.