2D Array printing in one column error - java

Please keep in mind my switch statement is not complete yet. I'm trying to figure out why that when I try and print intArray everything comes out in a single column. If anyone needs details don't hesitate to ask.
import java.util.*;
public class twoDimensionalArray
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int choice, row, col, upper, lower;
System.out.println("Choose the number of rows for the array");
row = console.nextInt();
System.out.println("Choose the number of columns for the array");
col = console.nextInt();
int[][] intArray = new int[row][col];
choice = Menu();
switch(choice)
{
case 1:
do
{
System.out.println("Choose a lower bound for the random numbers");
lower = console.nextInt();
System.out.println("Choose an upper bound for the random numbers");
upper = console.nextInt();
if (lower > upper)
{
System.out.println("The lower bound must be less than the upper bound");
}
}
while (lower > upper);
fillArray(intArray, upper, lower);
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: System.exit(0);
}
}
public static int Menu()
{
Scanner console = new Scanner(System.in);
int choice;
do
{
System.out.println("Enter the number corresponding to your choice:\n"
+ "1) Fill the array with new values \n"
+ "2) Find largest element \n"
+ "3) Find smallest element \n"
+ "4) Find Sum of elements \n"
+ "5) Find average of elements \n"
+ "6) Count the number of even elements \n"
+ "7) Total the odd values \n"
+ "8) FindIt \n"
+ "9) Print Array \n"
+ "10) Exit");
choice = console.nextInt();
}
while (choice < 1 || choice > 10);
return choice;
}
public static int[][] fillArray(int[][] intArray, int upper, int lower)
{
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
intArray[row][col] = lower + (int)(Math.random() * ((upper - lower) + 1));
}
}
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}
return intArray;
}//end fillArray
}//end program

There's a difference between System.out.println() and System.out.print().
Your code:
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}
My code:
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.print(intArray[row][col]);
}
System.out.println("");
}
print() prints the String argument, whereas println() prints the argument followed by a new line. I also added an additional call to println() between the rows so that they'll print out on their own lines.

System.out.println(intArray[row][col]) - println will end every print with a new line. To avoid this, use system.out.print()

Related

How can I make my code go from one void to another in my menu code and get it to randomly generate inputs?

My menu code (main) and the testMatrix code do not work properly, the menu code only improperly goes to the GetMatrix method (it has the user input a 4x4 matrix instead of the desired 3X4 and the testMatrix code doesn't even work, as it just uses the user input method instead. The program has asked me to change many of the program headers to make the code even run without crashing.
package sumelementsbycolumn;
import java.util.Random;
import java.util.Scanner;
public class SumElementsByColumn
{
private final static Scanner myScan = new Scanner(System.in);
//========================= void main() ==============================
public static void main(String[] args)
{
char choice;
do
{
final int ROWS = 3;
final int COLUMNS = 4;
double[][] matrix = new double[ROWS][COLUMNS];
choice = getMenu();
switch (choice)
{
case '1':
{
matrix = GetMatrix(matrix);
sumColumn(matrix);
sumPrint(matrix);
break;
}
case '2':
{
matrix = testMatrix(matrix);
sumColumn(matrix);
sumPrint(matrix);
break;
}
case '0':
System.out.println("\n==================================");
System.out.println("\n= Thank You for Using The ="
+ "\nSum Elements By Column Determiner");
System.out.println("\n= Goodbye! =");
System.out.println("\n==================================");
}
}while(choice != '0');
}
//========================= char GetMenu() ===========================
private static char getMenu()
{
System.out.print("===================================\n"
+ "=Sum Elements By Column Determiner=\n"
+ "===================================\n\n"
+ "\t(1) Input 3 rows of integers\n"
+ "\t(2) Test system using random numbers\n"
+ "\t(0) Exit the program\n"
+ "Choose: ");
char choice = myScan.next().toUpperCase().charAt(0);
return choice;
}
//========================= void sumPrint() ==============================
private static void sumPrint(double[][] theMatrix)
{
// Read a 3-by-4 matrix
final int ROWS = 3;
final int COLUMNS = 4;
double[][] matrix = new double[ROWS][COLUMNS];
GetMatrix(matrix);
// Display the sum of each column
for (int col = 0; col < matrix[0].length; col++)
{
System.out.println(
"Sum of the elements at column " + col +
" is " + sumColumn(matrix));
}
}
//========================= double getMatrix() ===========================
private static double[][] GetMatrix(double[][] matrix)
{
final int ROWS = 3;
final int COLUMNS = 4;
double[][] m = new double[ROWS][COLUMNS];
// Prompt the user to enter a 3-by-4 matrix
System.out.println("Enter a " + ROWS + "-by-" +
COLUMNS + " matrix row by row:");
for (int row = 0; row < m.length; row++)
for (int col = 0; col < m[row].length; col++)
m[row][col] = myScan.nextDouble();
while(!myScan.hasNextDouble())
{
System.out.println("That is not a valid number!");
System.out.println("Re-Enter the Matrix Values: ");
myScan.next();
}
return m;
}
//========================= double sumColumn() ===========================
public static double sumColumn(double[][] m)
{
double sum = 0;
int columnIndex = 0;
for (double[] m1 : m)
{
sum += m1[columnIndex];
}
return sum;
}
//========================= double testMatrix() ===========================
private static double[][] testMatrix(double[][] blankMatrix)
{
Random rnd = new Random();
int count = 0;
for (double[] blankMatrix1 : blankMatrix)
{
for (int col = 0; col < blankMatrix.length; col++)
{
{
blankMatrix1[col] = rnd.nextInt(100);
}
}
}
return blankMatrix;
}
}
I had tweaked the code a bit.This should work. Issue is in the sumColumn method that has the column index always set as 0.
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class SumElementsByColumn
{
private final static Scanner myScan = new Scanner(System.in);
//========================= void main() ==============================
public static void main(String[] args)
{
char choice;
do
{
final int ROWS = 3;
final int COLUMNS = 4;
double[][] matrix = new double[ROWS][COLUMNS];
choice = getMenu();
switch (choice)
{
case '1':
{
matrix = GetMatrix(matrix);
// sumColumn(matrix);
sumPrint(matrix);
break;
}
case '2':
{
matrix = testMatrix(matrix);
// sumColumn(matrix);
sumPrint(matrix);
break;
}
case '0':
System.out.println("\n==================================");
System.out.println("\n= Thank You for Using The ="
+ "\nSum Elements By Column Determiner");
System.out.println("\n= Goodbye! =");
System.out.println("\n==================================");
}
}while(choice != '0');
}
//========================= char GetMenu() ===========================
private static char getMenu()
{
System.out.print("===================================\n"
+ "=Sum Elements By Column Determiner=\n"
+ "===================================\n\n"
+ "\t(1) Input 3 rows of integers\n"
+ "\t(2) Test system using random numbers\n"
+ "\t(0) Exit the program\n"
+ "Choose: ");
char choice = myScan.next().toUpperCase().charAt(0);
return choice;
}
//========================= void sumPrint() ==============================
private static void sumPrint(double[][] theMatrix)
{
// Read a 3-by-4 matrix
final int ROWS = 3;
final int COLUMNS = 4;
// double[][] matrix = new double[ROWS][COLUMNS];
//GetMatrix(matrix);
// Display the sum of each column
for (int col = 0; col < theMatrix[0].length; col++)
{
System.out.println(
"Sum of the elements at column " + col +
" is " + sumColumn(theMatrix,col));
}
}
//========================= double getMatrix() ===========================
private static double[][] GetMatrix(double[][] matrix)
{
final int ROWS = 3;
final int COLUMNS = 4;
double[][] m = new double[ROWS][COLUMNS];
// Prompt the user to enter a 3-by-4 matrix
System.out.println("Enter a " + ROWS + "-by-" +
COLUMNS + " matrix row by row:");
for (int row = 0; row < m.length; row++) {
for (int col = 0; col < m[row].length; col++) {
m[row][col] = myScan.nextDouble();
}
}
while(!myScan.hasNextDouble())
{
System.out.println("That is not a valid number!");
System.out.println("Re-Enter the Matrix Values: ");
myScan.next();
}
return m;
}
//========================= double sumColumn() ===========================
public static double sumColumn(double[][] m,Integer col)
{
double sum = 0;
int columnIndex = 0;
// System.out.println(Arrays.deepToString(m));
for (double[] m1 : m)
{
// System.out.println(" sumcolumn "+m1[col]);
sum += m1[col];
}
return sum;
}
//========================= double testMatrix() ===========================
private static double[][] testMatrix(double[][] blankMatrix)
{
Random rnd = new Random();
int count = 0;
for (double[] blankMatrix1 : blankMatrix)
{
for (int col = 0; col < blankMatrix.length; col++)
{
{
blankMatrix1[col] = rnd.nextInt(100);
}
}
}
return blankMatrix;
}
}
Input Array for test:
===================================
=Sum Elements By Column Determiner=
===================================
(1) Input 3 rows of integers
(2) Test system using random numbers
(0) Exit the program
Choose: 1
Enter a 3-by-4 matrix row by row:
1 2 3 4
5 6 7 8
9 10 11 12
Output:
Sum of the elements at column 0 is 15.0
Sum of the elements at column 1 is 18.0
Sum of the elements at column 2 is 21.0
Sum of the elements at column 3 is 24.0

How to accept values within a certain range 2d array

I was wondering how to i set a range between certain number when entering numbers in?
Thanks
I tried using a do loop but it just kept looping even when i entered numbers within the range
public static void main(String args[])
{
int row, col, i, j;
int a[][]=new int[10][10];
do{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the order of a square matrix :");
row=sc.nextInt();
col=sc.nextInt();
/* checking order of matrix and then if true then enter the values
* into the matrix a[][]
*/
if(row == col)
{
System.out.println("Enter elements in the matrix:"+row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
a[i][j]=sc.nextInt();
}
}
} while(row != col);
// Display the entered value
System.out.println ("You have entered the following matrix");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
System.out.print (a[i][j] + " ");
System.out.println ();
}
First of all you should learn to extract tasks in methods and add Javadoc to make your code easier to read.
Hope this helps you:
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int dimension;
System.out.println("Enter the dimension of a squared matrix :");
dimension = sc.nextInt();
final int col = dimension;
final int row = dimension;
int[][] matrix = fillMatrix(row, col);
displayMatrix(matrix);
}
/**
* Prints the given matrix to console
*
* #param matrix to be printed
*/
private static void displayMatrix(int[][] matrix) {
System.out.println("You have entered the following matrix");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
/**
* Uses users input to fill create a matrix with the given dimensions
*
* #param row matrix row dimension
* #param col matrix column dimension
*
* #return a filled matrix
*/
private static int[][] fillMatrix(final int row, final int col) {
System.out.println("Enter elements in the matrix:" + row * col);
int[][] matrix = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmpNumber = 0;
while(tmpNumber<15 || tmpNumber >60){
System.out.println(String.format("Enter value for row %s, column %s between 15 and 60", i, j));
tmpNumber = sc.nextInt();
}
matrix[i][j] = tmpNumber;
}
}
return matrix;
}
Output:
Enter the dimension of a squared matrix :
2
Enter elements in the matrix:4
Enter value for row 0, column 0 between 15 and 60
2
Enter value for row 0, column 0 between 15 and 60
17
Enter value for row 0, column 1 between 15 and 60
18
Enter value for row 1, column 0 between 15 and 60
19
Enter value for row 1, column 1 between 15 and 60
20
You have entered the following matrix
17 18
19 20
First add the bounds as constant
final int LOWER_BOUND = 0;
final int UPPER_BOUND = 100;
Then check in the loop each entered value against the bounds before adding the value to the array
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
The problem remaining is that you can't use you for loops as they are now since the user might need several iterations to enter the right value. One simple solution is to surround the above code in a infinite while loop that is not exited until a correct value is given.
while (true) {
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
break;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
}
A better solution might be to replace the innermostfor loop with a while loop where you increase j manually when a correct value has been entered
This is simple example for your cause.
public static void main(String[] args) {
int number;
String getInputLine;
Scanner sc = new Scanner(System.in);
int a[][] = new int[10][10];
// for number of rows in your array
for (int i = 0; i < a.length; i++) {
// for number of columns in your array
for (int j = 0; j < a[0].length; j++) {
// print this message on screen
System.out.print("Enter your number: ");
// get input from next line
getInputLine = sc.nextLine();
//if you haven't match one or more integers
while (!getInputLine.matches("\\d{1,}")) {
System.out.print("Error! You inputted an invalid passcode, try again: ");
getInputLine = sc.nextLine(); // Prints error, gets user to input again
}
number = Integer.parseInt(getInputLine); // parse input into an integer
a[i][j] = number; // store it to array at position i j
System.out.println("You've set number " + number + " for array[" + i + " " + j + "]"); // Prints the passcode
}
}
//print your array
System.out.println(Arrays.deepToString(a));
}
}

Printing spaces to align numbers according to my pyramid pattern

It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.

User Input java 2d Array

I need to create code that takes user input to create the size of the 2d array (rows and columns must be less than 6), then fill it up with values that the user gives (between -10 and 10). My loop for taking the values isn't working at all and I'm not sure why. Here's the code
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
// create loop for accepting values within the matrix
// first loop for row values
for (int i = 0; i < userArray.length; i++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix rows");
int rowValues = input.nextInt();
while (rowValues > 10 || column < -10) {
System.out.println(
"Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
rowValues = input.nextInt();
}
// second embedded loop for column values
for (int j = 0; j < userArray[i].length; j++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix columns");
int columnValues = input.nextInt();
while (columnValues > 10 || column < -10) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter a number between 10 and -10.");
columnValues = input.nextInt();
}
}
}
printMatrix(userArray);
}
Couple of things here. First, your for-loop has two separate loops for the rows and columns. I assume what you're going for is prompting the user for each individual cell of the 2D array, which would require two nested loops. Second, at no point does your code example assign the user input to a variable, so I presume your output is just a bunch of 0 values?
You're probably looking for something more like this:
for (int i = 0; i < userArray.length; i++)
for(int j = 0; j < userArray[i].length; j++)
{
System.out.println("Please enter numbers between -10 and 10 for your matrix");
int valueIn = input.nextInt();
while (valueIn > 10 || valueIn < -10)
{
System.out.println("Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
valueIn = input.nextInt();
}
userArray[i][j]=valueIn;
}
You need a nested loop, to read values at row and then column level.
Something like below:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
for(int i=0;i< row ; i++){
for(int j=0; j< column; j++) {
System.out.print("Please enter the value for array["+i+"]["+j+"] (between -10 and 10):");
int val = input.nextInt();
if(val>10 || val< -10) {
System.out.println("Invalid value.");
continue;
}
userArray[i][j] = val;
}
}
printMatrix(userArray, row, column);
}
public static void printMatrix(int[][] array, int row, int column) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows.");
int rows = getValueFromConsole(scan, 1, 5);
System.out.println("Enter number of columns.");
int cols = getValueFromConsole(scan, 1, 5);
System.out.println("Enter matrix data.");
int[][] matrix = createMatrix(scan, rows, cols, -99, 99);
printMatrix(matrix);
}
private static int[][] createMatrix(Scanner scan, int rows, int cols, int min, int max) {
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = getValueFromConsole(scan, min, max);
return matrix;
}
private static int getValueFromConsole(Scanner scan, int min, int max) {
while (true) {
System.out.format("Number [%d:%d]: ", min, max);
int val = scan.nextInt();
if (val >= min && val <= max)
return val;
System.out.println("Sorry. Your number is not correct. Try again.");
}
}
private static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.format("%4d", matrix[row][col]);
System.out.println();
}
}
}
Output:
Enter number of rows.
Number [1:5]: 3
Enter number of columns.
Number [1:5]: 3
Enter matrix data.
Number [-99:99]: 10
Number [-99:99]: -11
Number [-99:99]: 12
Number [-99:99]: -13
Number [-99:99]: 14
Number [-99:99]: -15
Number [-99:99]: 16
Number [-99:99]: -17
Number [-99:99]: 18
10 -11 12
-13 14 -15
16 -17 18

Working With 2D Arrays in Java [duplicate]

This question already has answers here:
Summing Up A 2D Array
(3 answers)
Closed 9 years ago.
I'm trying to repost this question but with more clarification. Given my code below, I wish to output the total of each column and each row. The row totals should be to the right of the last element in that particular row and the column total should be below the final element in a given column. Please see the comment in the beginning of my program to understand what I wish my output to be. How could I go about doing this? Also I want to print out the main diagonal of a given user-inputted array. So in the code below the main diagonal would be outputted as {1,3,5}. Thank you!
/*
1 2 3 Row 0: 6
2 3 4 Row 1: 9
3 4 5 Row 2: 12
Column 0: 6
Column 1: 9
Column 2: 12
*/
import java.util.Scanner;
import java.util.Arrays;
public class Test2Darray {
public static void main(String[] args) {
Scanner scan =new Scanner(System.in); //creates scanner object
System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array
int rows = scan.nextInt(); //takes input for response
System.out.println("How many columns to fill?");
int columns = scan.nextInt();
int[][] array2d=new int[rows][columns]; //array for the elements
for(int row=0;row<rows;row++)
for (int column=0; column < columns; column++)
{
System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input
array2d[row][column]=scan.nextInt(); //Takes in current input
}
for(int row = 0; row < rows; row++)
{
for( int column = 0; column < columns; column++)
{
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
System.out.println("\n");
}
}
}
int[] colSums = new int[array2d.length];
int[] mainDiagonal = new int[array2d.length];
for (int i = 0; i < array2d[0].length; i++) {
int rowSum = 0;
for (int j = 0; j < array2d.length; j++) {
colSums[j] += array2d[i][j];
rowSum += array2d[i][j];
System.out.print(array2d[i][j] + " ");
if (i == j) mainDiagonal[i] = array2d[i][j];
}
System.out.println(" Row " + i + ": " + rowSum);
}
System.out.println();
for (int i = 0; i < colSums.length; i++)
System.out.println("Column " + i + ": " + colSums[i]);
System.out.print("\nMain diagonal: { ");
for (Integer e : mainDiagonal) System.out.print(e + " ");
System.out.println("}");

Categories