I am absolutely stuck. Any help would be appreciated. The question asks
1.Create two 2-dim arrays/matrices (random numbers, range 1 -500, where 1 and 500 should be declared as class constants). Both have the same dimensions.
2.Print the arrays.
3.Call a method to sum the 2 matrices. The sum of 2 matrices matrix_1 and matrix_2 is a matrix result, where for every row r and column c,
result_rc= matrix_1_rc+ matrix_2_rc
4.Print the resulting matrix.
I am stuck on 3 and 4. Part of the problem is I do not get the logic of what 3 is asking. Do I get the sum of each row and each column and add that to the second arrays sum of rows and columns. The second problem is I am absolutely lost on what to do next.
I have been researching for hours and trying different things.
import java.util.*;
public class Lab12p2 {
public static final int MAX = 500;
public static final int MIN = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of times to run the program");
int start = scan.nextInt();
while (start < 0) {
System.out.println("Error! Should be positive. REENTER");
start = scan.nextInt();
}
// end number of times validation
while (start > 0)// counter loop for how many times to run program {
System.out.println("Enter the size of the 2 arrays");
int SIZE = scan.nextInt();
while (SIZE < 0) {
System.out.println("Error! Should be positive. REENTER");
SIZE = scan.nextInt();
} // size validation
// start of methods
int[][] a = new int[SIZE][SIZE];
int[][] b = new int[SIZE][SIZE];// second array
System.out.println("The first array is ");
System.out.println();
randArray(a, SIZE, SIZE, MIN, MAX);
System.out.println("The second array is ");
System.out.println();
randArray(b, SIZE, SIZE, MIN, MAX);
sum2arrays(a, b, SIZE, SIZE);
start--;
}
public static void randArray(int[][] matrix, int row, int col, int low, int up) {
Random rand = new Random();
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
int random = matrix[r][c] = rand.nextInt(up - low + 1) + low;
System.out.print("\t" + random);
}
System.out.println();
}
}
public static void sum2arrays(int[][] matrix1, int[][] matrix2, int col, int row) {
int sumrow;
int sumtotalrow = 0;
for (int r = 0; r < matrix1.length; r++) {
sumrow = 0;
for (int c = 0; c < matrix1[r].length; c++) {
sumrow = sumrow + matrix1[r][c];
}
sumtotalrow = sumtotalrow + sumrow;
}
// testing
System.out.println("The sum of ALL the elements/row = " + sumtotalrow);
}
}
It should
Call a method to sum the 2 matrices. The sum of 2 matrices matrix_1 and matrix_2 is a matrix result, where for every row r and column c,
result_rc= matrix_1_rc+ matrix_2_rc (I dont know what that means) and then print the resulting matrix
public static void sum2arrays(int[][] matrix1, int[][]matrix2,int col,int row)
{
int sumrow;
ArrayList <Integer> three=new ArrayList<Integer>();
for (int r = 0; r < matrix1.length; r++)
{
sumrow = 0;
for (int c = 0; c < matrix1[r].length; c++)
{
three.add( matrix2[r][c] + matrix1[r][c]);
}
}
System.out.println("The matrix result is ");
System.out.println(three);
}
Related
The goal of this is to print out the size of the blob when given a set of coordinates within a 10 x 10 matrix. It's written in java and the point of the exercise was to use recursion to find each of the 1's in the blob. (Any 1's that are connected to the original coordinate by going up, down, left, or right.
Example:
The Blob
0010010010
0100100101
1001001010
0011110101
0111101010
1001010100
0010101101
0101010010
1010100100
0101001000
The Coordinates
1 1
2 3
5 7
The Output
1
10
3
import java.util.*;
public class BlobsRunner
{
public static void main(String[] args)
{
//test the Blob class to make sure
//it works as intended
Blobs bloop = new Blobs(10, 10);
//call both constructors
Scanner reader = new Scanner(System.in);
System.out.println("Row: ");
int r = reader.nextInt();
System.out.println("Colum: ");
int c = reader.nextInt();
bloop.recur(r, c);
bloop.getBlobCount();
//print the newly instantiated Blob
bloop.toString();
//call methods - print out the size of the blob
//bloop.getBlobCount();
}
}
//next file
import java.util.*;
public class Blobs
{
private int[][] mat; //grid of 1s and 0s
private int count;
private int[][] visited;
public Blobs( int rows, int cols )
{
//set count to 0
count = 0;
//point mat at new mat size rows X cols
mat = new int[rows][cols];
//loop through mat
for(int a = 0; a < rows; a ++)
{
for(int b = 0; b< cols; b++)
{
mat[a][b] = (int)Math.random();
}
}
//fill in mat with 1s and 0s
//use Math.random()
visited = new int[rows][cols];
}
public Blobs( int rows, int cols, String s )//what does s mean?
{
//set count to 0
count = 0;
//point mat at new mat size rows X cols
mat = new int[rows][cols];
for(int a = 0; a < rows; a ++)
{
for(int b = 0; b< cols; b++)
{
mat[a][b] = (int)Math.random();
}
}
visited = new int[rows][cols];
//loop through mat
//load in the 1s and 0s from s
}
public void recur(int r, int c)
{
//add a base case
if(mat[r][c]==0)
{
//return;
}
if(visited[r][c] == 5)//figure out, make sure it doesn't count if it does
{
//return;
}
visited[r][c] = 5;
//mark current pos as visited
count++;
//increase count by 1
//add in 4 recursive calls
//UP
if(mat[r+1][c] == 1 && visited[r+1][c] != 5)
{
recur(r+1, c);
}
//DOWN
if(mat[r-1][c] == 1 && visited[r-1][c] != 5)
{
recur(r-1,c);
}
//LEFT
if(mat[r][c-1] == 1 && visited[r][c-1] != 5)
{
recur(r,c-1);
}
//RIGHT
if(mat[r][c+1] == 1 && visited[r][c+1] != 5)
{
recur(r,c+1);
}
}
public int getBlobCount()
{
//return count
return 0;
}
public String toString()
{
//you will need nested loops
//you will need a local string variable
for(int a = 0; a < mat.length; a++)
{
for(int b = 0; b < mat[a].length; b++)
{
System.out.print(mat[a][b]);
}
System.out.println();
}
return "";
}
}
Math.random() function returns double values between 0 to 1 so when you try to convert it to (int) it becomes 0. So all of your matrix is 0. And since you are doing nothing at recur() function its print 10x10 0 matrix.
Try adding import java.util.Random; then Random r = new Random(); and when you assign random numbers mat[a][b] = r.nextInt(2);
As #Fatih Aslan noted, Math.random() produces a double between 0.0 and 1.0, not including 1.0. When parsed to an int, Java will always produce the value 0.
If you do not want to use the java.util.Random library you can multiply the value you are obtaining from Math.random() by the difference between the highest and lowest random numbers you would like to generate, plus 1. If you want your lowest possible random number to be greater than 0, add that number to the output of Math.random().
For example, (int)(2 + (Math.random() * 9)) will produce random integers from 2 to 10 including 2 and 10.
"Find the maximum element (s) in the matrix and remove from the matrix all the rows and columns containing it".
I made the methods. In one, I find the largest number in the matrix. And in the second, I delete from the matrix the row and column that contains the largest number. But it works correctly only if the largest number is the only one. How to make, that deleted all lines and all columns in which the greatest number contains?
private void deleteRowCol() {
int[][] matrix = getMatrix();
int max = matrix[0][0];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (max < matrix[i][j]) {
max = matrix[i][j];
}
}
}
int[] m = findIdMax(matrix, max);
int[][] outMatrix = new int[matrix.length - 1][matrix[0].length - 1];
int r = 0;
for (int i = 0; i < outMatrix.length; i++) {
if (i > m[0] - 1) {
r = 1;
}
int c = 0;
for (int j = 0; j < outMatrix[0].length; j++) {
if (j > m[1] - 1) {
c = 1;
}
outMatrix[i][j] = matrix[i + r][j + c];
}
}
System.out.println(" ");
outputMatrix(outMatrix);
}
private int[] findIdMax(int[][] matrix, int max) {
int[] id = {0, 0};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (max == matrix[i][j]) {
id[0] = i;
id[1] = j;
}
}
}
return id;
}
expected output:
with this matrix
4 2 0 -3
4 -1 4 1
0 2 -4 3
-4 -1 -4 -2
should bring
-2 3
-1 -2
I haven't been able to find a fix for your current code. One issue is that you always assume 1 row and 1 column are deleted with int[][] outMatrix = new int[matrix.length - 1][matrix[0].length - 1];. If I put a loop around your code it would fail if the max is for example at positions 1,2 and 1,4 in the matrix (which should remove only 1 row, but 2 columns).
So perhaps someone else could take a closer look at your implementation and see a straight-forward fix without changing too much. Instead, I've thought about the use case from scratch and tried to complete the task myself. I ended up with the following code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Main{
private Set<Integer> rowsToDelete,
columnsToDelete;
public static void main(String[] a){
Main program = new Main();
int[][] matrix = program.getMatrix();
System.out.println("Before:");
program.prettyPrintMatrix(matrix);
System.out.println();
int[][] modifiedMatrix = program.deleteRowCol(matrix);
System.out.println("After:");
program.prettyPrintMatrix(modifiedMatrix);
}
private int[][] getMatrix(){
// Test:
return new int[][]{
{ 4, 2, 0,-3},
{ 4,-1, 4, 1},
{ 0, 2,-4, 3},
{-4,-1,-4,-2}
};
}
private int[][] deleteRowCol(int[][] matrix) {
int max = findMax(matrix);
determineCoordinatesMax(matrix, max);
// Some debug prints:
System.out.println("Maximum: "+max);
System.out.println("Rows to delete: "+rowsToDelete);
System.out.println("Columns to delete: "+columnsToDelete);
System.out.println();
int[][] modifiedMatrix = deleteRows(matrix);
modifiedMatrix = deleteColumns(modifiedMatrix);
return modifiedMatrix;
}
private int findMax(int[][] matrix){
int max = matrix[0][0];
for(int[] row : matrix){
for(int value : row){
if(value > max){
max = value;
}
}
}
return max;
}
private void determineCoordinatesMax(int[][] matrix, int max) {
rowsToDelete = new HashSet<>();
columnsToDelete = new HashSet<>();
for(int r=0; r<matrix.length; r++){
for(int c=0; c<matrix[r].length; c++){
if(matrix[r][c] == max){
rowsToDelete.add(r);
columnsToDelete.add(c);
}
}
}
}
private int[][] deleteRows(int[][] matrix){
int rowsToLeave = matrix.length - rowsToDelete.size();
int[][] modifiedMatrix = new int[rowsToLeave][];
int i = 0;
for(int r=0; r<matrix.length; r++){
if(!rowsToDelete.contains(r)){
modifiedMatrix[i] = matrix[r];
i++;
}
}
return modifiedMatrix;
}
private int[][] deleteColumns(int[][] matrix){
int columnsAlreadyDeleted = 0;
for(int columnToDelete : columnsToDelete){
// Delete the columns one by one:
int[][] modifiedMatrix = new int[matrix.length][matrix[0].length - 1];
for(int r=0; r<matrix.length; r++){
int i=0;
for(int c=0; c<matrix[r].length; c++){
if(c != columnToDelete - columnsAlreadyDeleted){
modifiedMatrix[r][i] = matrix[r][c];
i++;
}
}
}
columnsAlreadyDeleted++;
matrix = modifiedMatrix;
}
return matrix;
}
private void prettyPrintMatrix(int[][] matrix){
for(int[] row : matrix){
System.out.println(Arrays.toString(row));
}
}
}
The deletion of the columns could use some tweaking, since I now have three nested loops (loop over the columns to delete; inner loop over the matrix-rows; inner loop over the matrix-columns). But it works, and removes the rows and columns of the int[][] as expected.
You can see it in action here: Try it online.
The output of this program works fine. But there's one thing I've not been able to implement. In some cases, I don't have a row or column with the highest number of 1s. Sometimes I have 2 or more rows/columns which have the same "HIGHEST" number of ones. But my program only returns 1 row/column.
I want a case whereby If i have more than 2 rows/columns with the same highest number of 1s. Both rows will be displayed. e.g. "Row(s) with the most 1's: 1,2" or if it's a column it can say "Row(s) with the most 1's: 1,2".
Please I need help with this. I'm stuck.
import java.util.Random;
import java.util.Scanner;
public class LargestRowColumn
{
// declare a 2 dimensional array or an array of arrays
private static int[][] randArray;
public static void main(String[] args)
{
do
{
// Create a scanner to get Input from user.
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter the array size n:");
int rows = scanner.nextInt();
int cols = rows;
randArray = new int[rows][cols];
// loop through the number of rows in thw array
for (int i = 0; i < randArray.length; i++)
{
// loop through the elements of the first array in the array
for (int j = 0; j < randArray[0].length; j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
}
// make a linebreak each row.
System.out.println();
}
System.out.print("Row(s) with the most 1's: " + scanRow(randArray) + "\n");
System.out.print("Columns(s) with the most 1's: " + scanColumn(randArray) + "\n");
}
while(true);
}
// quick method I made to get a random int with a min and max
public static int getRandomInt(int min, int max)
{
Random rand = new Random();
return rand.nextInt(max-min+1)+min;
}
public static int scanRow(int[][] array)
{
int result = -1;
int highest = -1;
for (int row = 0; row < array.length; row++)// Here we are about start looping through the matrix values
{
int temp = 0; // Setting the first index to 0.
for (int col = 0; col < array[row].length; col++)//
{
//Assign current location to temporary variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = row + 1;
}
}
return result;
} // end of row method
private static int scanColumn(int[][] array)
{
int result = -1;
int highest = -1;
// declare and initialize the variable(here you've 'created' it, to then call it on if statement)
int col = 0;
for (int row = 0; row < array.length; row++)
{
int temp = 0;
//declare the variable in the for loop
for (col = 0; col < array[row].length; col++)
{
//Assign current location to temp variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = col;
}
}
return result;
}
}
I would suggest a different approach, first thing why do you need to loop all over the 2D array again , u can figure out the highest 1's in rows and columns while inserting them and insert them in an array ( array of rows and array for columns) the carry will be of custom type which is a class with two parameters , score(which is number of 1's) and index( which is the number of the row or column), then sort the arrays and print the indexes related to top scores.
if you are expecting to receive the array with the inputs you can do the same but with new loop.
so your insert loop will be like this
List<Wrapper> rowsList = new ArrayList<Wrapper>(rows);
List<Wrapper> colsList = new ArrayList<Wrapper>(cols);
for(int i=0;i<cols;i++) {
colsList.add(new Wrapper(i,0));
}
// loop through the number of rows in thw array
for (int i = 0; i < rows; i++)
{
int sum =0;
// loop through the elements of the first array in the array
for (int j = 0; j < cols j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
sum+=randArray[i][j];//add for row
colsList.get(j).setScore(colsList(j).getScore() +randArray[i][j]);//add for column
}
rowsList.add(new Wrapper(i,sum));
// make a linebreak each row.
}
Collections.sort(rowsList,new Comparator<Wrapper>() {
#Override
public int compare(Wrapper obj1,Wrapper obj2) {
if(obj1.getScore() > obj2.getScore())
return -1;
if(obj1.getScore() < obj2.getScore())
return 1;
return 0;
}
});
if(rowsList.isEmpty())
return -1;
int max = rowsList.get(0).getScore();
for(Wrapper obj:rowsList) {
if(obj.getScore()< max)
break;
System.out.println(obj.getIndex);
}
//DO THE SAME FOR COLUMNS
your wrapper class will be
public class Wrapper {
private int index;
private int score;
public Wrapper(int index,int score) {
this.index = index;
this.score = score;
}
public int getIndex() {
return this.index;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score
}
}
This is in keeping with the OP use of arrays.
Instead of returning an int, which would be one row, you can return int[].
Personally, I would init the int[] to the number of rows in the array, because what if every row has the same number of 1's?
int[] results = new int[array[0].length];
Then, instead of adding in the rows, I would have a variable used to designate which spot to add the row to, i.e., results[0] etc.
int index = 0;
Then, all it takes is a small adjustment to how you add your results to the array.
public static int[] scanRow(int[][] array)
{
int highest = -1;
int index = 0; //ADD HERE
int[] results = new int[array[0].length]; //ADD HERE
... //Your code here
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
for(int x = 0; x < results.length; x++){
results[x] = -1;
}
index = 0; //RESET THE INDEX
results[index] = row + 1;
index ++;
} else if (temp == highest{
highest = temp;
results[index] = row + 1;
index ++;
}
}
return results;
} // end of row method
Personally, I would use an ArrayList for these types of things, so heres how I would do it using it.
I would make the return type of the method an ArrayList<int>.
public static ArrayList<int> scanRow(int[][] array)
Then declare my ArrayList<int>
ArrayList<int> results = new ArrayList<>();
and the if statements are a little easier to handle, since ArrayList as a clear() and add() method.
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
results.clear();
results.add(row+1);
} else if (temp == highest{
highest = temp;
results.add(row + 1);
}
EDIT
Don't forget to edit your print statements accordingly.
I think I confused the methods and can't get the actual methods correct. Please help, the array needs to rotate to the right where the first digit will become the last digit. I generate a random array based on size that the user input. Then I print that array, then do the rotation, then print the new array with the first digit last and the last digit first.
import java.util.Scanner;
import java.util.Random;
public class modOne {
public static final int MIN = 1;
public static final int MAX = 15;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int arraySize = 0;
System.out.println("How many arrays to rotate right?");
int howMany = input.nextInt();
while(howMany <= 0) {
System.out.println("ERROR! Should be positive. REENTER: ");
howMany = input.nextInt();
}
while(howMany > 0) {
System.out.println("Enter array size: ");
arraySize = input.nextInt();
}
int[] a = new int[arraySize];
int[] b = new int[arraySize];
getRand(a, MIN, MAX);
System.out.println("The array before rotation: ");
printArray(a);
System.out.println("THe array after rotation: ");
transArray(a);
printArray(b);
System.out.println("Enter array size: ");
arraySize = input.nextInt();
}
public static void getRand (int[] list, int size, int low, int up) {
Random rand = new Random();
for(int r = 0; r < size; r++) {
list[r] = rand.nextInt(up - low + 1) + low;
}
}
public static void printArray(int[] list, int size) {
for (int r = 0; r < size; r++) {
System.out.printf("%5d", list[r]);
if(r % 6 == 5)
System.out.println();
}
System.out.println();
}
public static void transArray(int[] list, int size) {
for(int r = 0; r < size - 1; r++) {
list[r] = list[r-1];
}
}
}
You can make use of System.arrayCopy to copy sourceArray from start index to destination array from start index. You can also specify how many elements should e copied as last argument to System.arrayCopy method. See below:
int[] arr = new int[]{8, 15, 2,10, 11,15,1,3};
System.out.println("array before rotation: " + Arrays.toString(arr));
int lastElement = arr[arr.length -1 ];
System.arraycopy(arr, 0, arr, 1, arr.length-1);
arr[0] = lastElement;
System.out.println("array after rotation: " + Arrays.toString(arr));
I backup the last element and then copy the array entirely in a new array skipping the first element of the array and then I assign the first element of the array with the value that I backup early.
The output you get is as follow:
array before rotation: [8, 15, 2, 10, 11, 15, 1, 3]
array after rotation: [3, 8, 15, 2, 10, 11, 15, 1]
For more details on how System.arrayCopy works, you can see the following tutorial or read my answer in this question.
You just have to invert the order and save the value you are going to overwrite to recover it later. I also took the liberty to make some other changes to your code. Now it should work as intended.
while (howMany <= 0) {
System.out.println("ERROR! Should be positive. REENTER: ");
howMany = input.nextInt();
}
System.out.println("Enter array size: ");
arraySize = input.nextInt();
int[] a = new int[arraySize];
int[] b = new int[arraySize];
getRand(a, MIN, MAX);
System.out.println("The array before rotation: ");
printArray(a);
System.out.println("THe array after rotation: ");
printArray(transArray(a));
}
public static void getRand(int[] list, int low, int up) {
Random rand = new Random();
for (int r = 0; r < list.length; r++) {
list[r] = rand.nextInt(up - low + 1) + low;
}
}
public static void printArray(int[] list) {
for (int r = 0; r < list.length; r++) {
System.out.printf("%5d", list[r]);
if (r % 6 == 5) {
System.out.println();
}
}
System.out.println();
}
public static int[] transArray(int[] list) {
int temp1 = list[list.length - 1];
for (int r = list.length - 1; r > 0; r--) {
list[r] = list[r-1];
}
list[0] = temp1;
return list;
}
What you can do is use Arrays.copyOfRange(T[] original, int from, int to) in order to shift most of the array. Some numbers are cut off, though, and need to be placed back in afterwards.
public static void main( String[] args ) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
arr = rot(arr, -1);
System.out.println(Arrays.asList(arr));
}
public static int[] rot( int[] arr, int amt ) {
while ( amt < 0 )
amt += arr.length;
amt = amt % arr.length;
int[] k = Arrays.copyOfRange(arr, amt, arr.length + amt);
for ( int i = 0; i < amt; i++ )
k[k.length - amt + i] = arr[i];
return k;
}
rot() rotates left by amt, so using the parameter amt = -1 achieves what you set out to do.
The rot() method first forces 0 ≤ amt < arr.length. This is because once you rotate by the full length of the array, you're back where you started. Next it shifts the array by amt, adding the integer's default value (0) to the end as padding to preserve length. Finally, it adds the lost elements back into the array where the 0's were placed.
for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
The logic behind this is that you are swapping the values until you get to the center:
I made this image for you to better understand
Here, there is no center, but if there was a 3.5, then it would ignore the three point five because validData[validData.length - i - 1] = temp;
I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.