Multi-Dimesional Array with User Input - java

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

Related

Program that removes duplicated elements and return its new elements and size

My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}

How to get the average of ONE specific column in a 2D array?

The user enters the values into the array then I'd want to get the average of any specific column.
This is the code below:
public class Test2DProcess {
public static void main( String[] args ) {
int[][] gradesArray = new int [4][3];
Scanner input = new Scanner(System.in);
for (int i=0; i<4; i++) {
for (int j=0; j<3; j++){
System.out.println("Enter grade: ");
gradesArray [i][j] = input.nextInt();
}
}
}
}
Now let's say I want to sum up the values in the first column of this array then get the average...this would mean the values in positions (0,0)...(1,0)...(2,0)...(3,0) and (4,0) of the array. How would I go about doing so?
The same way can be useful, don't forget gradesArray is a [4][3] grid, so there is no (4,0) element
int incremental =0;
double ave = 0.0;
for (int i=0; i<4; i++)
{
incremental += gradesArray[0][i];
}
and then
ave = incremental / 4.0;
Edit: the average of each individual column stored in a variable to be printed later.
in your code you must calculate the sum in first for loop. Here is:
int[][] gradesArray = new int[4][3];
Scanner input = new Scanner(System.in);
int sumFirst = 0;
int sumSecond = 0;
int sumThird = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
System.out.println("Enter grade: ");
gradesArray[i][j] = input.nextInt();
}
sumFirst += gradesArray[i][0];
sumSecond += gradesArray[i][1];
sumThird += gradesArray[i][2];
}
double averageFirst = (double)sumFirst/4;
double averageSecond = (double)sumSecond/4;
double averageThird = (double)sumThird/4;

How to print out the array with all of the values?

I try to print the matrix AxA with all of the values are showed in there, but I failed.
Output should be something look like this:
1 2 3
4 5 6
Thank you
So this is my code:
import java.util.Scanner;
public class Lab2 {
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 < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j] = input.nextInt();
}
System.out.println(" " + array);
}
}
Updated:
I was able to print out the matrix, but now I run into the second question is calculating the average of each rows and columns of the matrix. I tried to use this code, but it didn't work, and I know that I have a major problem right here, but I couldn't find one.
I have been doing it since this morning until now. Not going to lie, this is my homework which to test my basic knowledge.
My new output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
ave=2.5, 3.5, 4.5
And this is my current code right now:
import java.util.Scanner;
public class Lab2 {
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");
}
}
public static doube 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;
}
public static doube 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;
}
}
You can use same logic for reading and writing array elements,Try this code
Reading an array...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
array[i][j] = input.nextInt();
}
}
Printing array elements...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
Use
Stream.of(array).map(Arrays::toString).forEach(System.out::println);
Which will print :
[1 ,2, 3]
[4, 5, 6]
or
System.out.println(Arrays.deepToString(array));
Reference
Keep in mind that you can't simply print the whole array. I.e.: System.out.println(" " + array);
You're on the right track but you need to print using a for loop (give printf a try, it's powerful):
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++){
System.out.printf("%d ", array[i][j]);
}
System.out.printf("\n");
}
There is another single loop way I can think of:
for (int[] a : array) {
String str = Arrays.toString(a);
System.out.println(str.substring(1, str.length()-1).replaceAll("[,]", ""));
}
The for loop basically iterates over each row, i.e. value of 'a' is an array (row) in the matrix.
Arrays.toString(a) returns the string equivalent of the array, e.g. for a = [1,2,3,4,5], it would return "[1, 2, 3, 4, 5]". Now simply remove the brackets (substring) and replace commas (",") with "", and you have the desired result.
Note that the first parameter of the replaceAll is a regex, not the string itself.

How do I fix my addition for summing a specific row and column in java?

I have all of my other methods that were required for my class program working properly, however I can not think of how to fix my row input and sum method and my column input and sum method. I also apologize for the ridiculously long method names, the methods for pre-named for the assignment.
import java.util.Scanner;
public class Two_D_Array_CMPS280_2016
{// begin class Two_D_Array_CMPS280_2016
public static void main(String args[])
{// begin main method
int[][] brianArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};// end array initialization
// Print segment to print values from methods for brianArray
System.out.print("The sum of all elements is " + Total_2DArray_Elements(brianArray));
System.out.print("\nThe average of all elements is " + Average_2DArray_Elements(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Row_Number(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Column_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Row_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Column_Number(brianArray));
}// end main method
public static void printArray(int[][] myArray)
{// begin to print arrrays
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}// end printArray method
public static int Total_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
}
}
return total;
}
public static int Average_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
int average = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
average = total / 16;
}
}
return average;
}// end method to sum array values
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[0].length; j++)
{
total += myArray[row][j];
}
}
return total;
}// end method to sum array by user input row
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[0].length; j++)
{
total += myArray[i][column];
}
}
return total;
}// end method to sum array by user input column
public static int The_Largest_Value_In_Certain_Row_Number(int[][] myArray)
{// begin method to return largest number by user input row
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the row you would like the highest value from: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
if (myArray[row][j] > highestValue)
highestValue = myArray[row][j];
}
}
return highestValue;
}// end method to return largest number by user input row
public static int The_Largest_Value_In_Certain_Column_Number(int[][] myArray)
{// begin method to return largest number by user input column
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the column you would like the highest value from: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[i].length; j++)
{
if (myArray[i][column] > highestValue)
highestValue = myArray[i][column];
}
}
return highestValue;
}// end method to return largest number by user input column
}// end class
Here is Java 8 magic, which will help u sum, average etc of any row or colum
int[][] intArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
//Sum specific column
int columnNo=0;
Integer sumOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).sum();
Double avgOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfColum);
//Sum of specific row
int rowNo=0;
Integer sumOfRow=Arrays.stream(intArray[rowNo]).sum();
Double avgOfRow=Arrays.stream(intArray[rowNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfRow);
Change your methods to the following, should do you good :
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int j = 0; j < myArray[0].length; j++) {
total += myArray[row][j];
}
return total;
}// end..
and
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++) {
total += myArray[i][column];
}
return total;
}// end m..

finding cofactor and determinant of a 3x3 matrix (java)

I computed the product, sum, and transpose(of product), but I have no clue where to start on the cofactor and determinent of the product matrix.
Ive seen a couple examples but none that resemble my particular code so if anyone could show me how i could incorporate these two methods into my program I'd high appreciate it.
please dont ask me what i've tried because as I stated I am clueless at the moment
//here is the code I wrote for the product:
package programEx;
import java.io.*;
import java.util.*;
import java.io.File.*;
import java.util.Scanner;
public class progEx {
public static void main(String[] args) {
//Establishing Input Stream
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];
//Taking user input for 1st matrix
System.out.println("Enter matrix A");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}
//Taking user input for 2nd matrix
System.out.println("Enter matrix B");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}
//calling the multiplication method and passing it to both matrices
int[][] c = multiply(a, b);
System.out.println("Product of A and B is");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
//Separate method for the multiplication of 1st and 2nd matrices
public static int[][] multiply(int[][] a, int[][] b) {
int rowsInA = a.length;
int columnsInA = a[0].length;
int columnsInB = b[0].length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}
Well,a 3*3 matrix has 3 columns and 3 rows to begin with.
Each starts with an index 0.
Determinant can be calculated as:
int d=determinant();
int determinant()
{
int x=a[0][0]*((a[1][1]*a[2][2])-(a[2][1]*a[1][2]));
int y=-a[0][1]*((a[0][1]*a[2][2])-(a[2][0]*a[1][2]));
int z=a[0][2]*((a[1][0]*a[2][1])-(a[1][1]*a[2][0]));
int r=x+y+z;
return r;
}
This is only for finding the determinant of a 3*3 matrix.

Categories