Working With 2D Arrays in Java [duplicate] - java

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

Related

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

Adding columns and rows in a 2D array of String type?

I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.

The values of the columns of my 2D array are averaging wrong with out of order inputs

I'm working on a code to produce a 2D array to hold user inputted values. I made a averaging function in the "print array for loop"but it messes up such as when column input (3 1 2) gives an average of output of (2 6 4). All the values of the array were set to 2 for testing. I can't figure out what is wrong with the loop. I'm new to java so I'm sorry if the answer is something obvious.
The table printed should look like this with row(3) and columns(3 1 2):
A:2.0 2.0 2.0 [3.0]
B:2.0 [2.0]
C:2.0 2.0 [2.0]
where the bracketed term holds the average and the 2.0 are the values held by the column.
The code:
// 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][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) {
sum += figures[row][col];
average = sum/figures[row].length;
System.out.print(" "+figures[row][col]);
System.out.print(" ");
}
System.out.printf("%1$5s","["+average+"]");
System.out.println();
}
}
PS: its a minor question, I'm using %1$5s to keep the bracket term 5 spaces from the printed columns, but I was wondering if there is a way to keep them all at the same length.
You need to add
sum = 0;
after
for(int row=0; row<figures.length; ++row) {
otherwise the totals are wrong when you calculate the average.
To pad out a string, there's a good answer on here already How can I pad a String in Java?. Look at the 2nd answer.
int minLen = 20;
String s = myformat(value, length);
int diff = minLen - s.length;
System.out.printf("%1$" + diff + "s", s);
Where String s is your formatted string using your above "[" + average + "]" stuff. The idea is that you have a minimum length string to work with so that your positioning is always the same.

Printing Custom 2d Array as a Matrix

Given my current code, how could I output it in matrix format? My current output method simply lists the arrays in a straight line. However I need to stack them in their corresponding input parameters so a 3x3 input produces a 3x3 output. Thank you!
import java.util.Scanner;
for(int row = 0; row < rows; row++){
for( int column = 0; column < columns; column++){
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
This will print out a line of one row and then move onto the next row and print out its contents, etc... Tested with the code that you provided and works.
EDIT - Added the code for the way you wanted it:
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
}
System.out.println(Arrays.deepToString(array2d));
String[][] split = new String[1][rows];
split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma
for(int row = 0; row < rows; row++){
System.out.println(split[0][row]);
}
scan.close();
}
for (int i =0; i < rows; i++) {
for (int j = 0; j < columns ; j++) {
System.out.print(" " + array2d[i][j]);
}
System.out.println("");
}

Beginner 2D-Array out of bounds exception

I'm having some difficulties trying to figure out how to implement a second array to calculate the averages of my marks program.
I'm using 1 2D array to store the scores each student received on each assignment
(5 students, 4 assignments).
I have managed to get the Students average array working but when I go to calculate each individual assignment mark (combined total of the 5 students /5 ). I keep getting an Indexoutofbounds exception, Im very new to 2d arays and am still trying to figure out how to read them properly.
Heres my code:
import java.util.Scanner;
public class Marks
{
private String[] names;
private int[][] assignments;
private double[] stuAvgArray;
private double[] assignAvgArray;
public Marks()
{
names = new String[5];
assignments = new int[5][4];
stuAvgArray = new double[5];
assignAvgArray = new double[4];
}
public void getInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter 5 student names: ");
for(int i = 0; i < names.length; i++)
names[i] = input.nextLine();
for(int row = 0; row < assignments.length; row++)
{
System.out.println("Enter the 4 marks for: " + names[row]);
for(int col = 0; col < assignments[row].length; col++)
{
assignments[row][col] = input.nextInt();
stuAvgArray[row] += assignments[row][col];
}
stuAvgArray[row] = (stuAvgArray[row]/4);
}
for (int col = 0; col < assignments.length; col++)
{
for(int row = 0; row < assignments[col].length; row++)
assignAvgArray[row] += assignments[row][col];
assignAvgArray[col] = (assignAvgArray[col]/5);
}
}
public String toString()
{
String output = ("Student \t\t\t Marks \t\t\t\t Average \n" +
"Name \t\t\t\t out of 10 \t\t\t out of 10 \n" +
"\t\t A1 \t A2 \t A3 \t A4");
for(int i = 0; i < assignments.length; i++)
{
output = output + "\n" + names[i];
for(int col = 0; col < assignments[i].length; col++)
{
output = output + "\t " + assignments[i][col] + "\t ";
}
output = output + "\t\t" + stuAvgArray[i];
output = output + "\n" + assignAvgArray[i];
}
return output;
}
}
i've bolded where java says the error is coming from. I am trying to read in, store, and then calculate for the array spots [[(0,0),(1,0),(2,0),(3,0),(4,0)],[(0,1),(1,1),(2,1),(3,1),(4,1)..etc]]
what Im trying to ask is how can I create a loop that doesn't give me this exception, storing all the values of each column into separate spots, and dividing each number stored in the new array by 5 to give me the average.
if there's anything else I can do to help you understand my problem please let me know.
PS: This is what It's supposed to look like;
Student Marks Average
Name out of 10 out of 10
A1 A2 A3 A4
Joe Smith 8 9 10 4 7.75
Tommy Jones 9 9 8 5 7.50
Sara Lee 0 10 10 9 7.25
Bob Fowler 10 9 9 0 7.00
Jane Doe 10 10 10 10 10.00
**Average 7.40 9.40 9.40 5.60**
I've calculated the row average but the bolded column average is giving me grief
The following line is wrong:
for(int row = 0; row < assignments[col].length; col++)
You are using row and increment col instead. As a result, you are doing an out of bound error in the block of that loop.
Replace it by:
for(int row = 0; row < assignments[col].length; row++)
But I'm afraid this is not the only problem. According to the way you read the input, assignments is a 2D-array with the row number for the first dimension and the column number for the second dimension. However, you are mixing the dimension here. As a reminder, you code is:
for (int col = 0; col < assignments.length; col++)
{
for (int row = 0; row < assignments[col].length; row++) {
assignAvgArray[row] += assignments[row][col];
}
assignAvgArray[col] = (assignAvgArray[col]/5);
}
As you can see, you are using col to identify the row. assignments.length is the number of lines.
for (int col = 0; col < assignments[0].length; col++)
{
for (int row = 0; row < assignments.length; row++) {
assignAvgArray[row] += assignments[row][col];
}
assignAvgArray[col] = (assignAvgArray[col]/5);
}
for (int col = 0; col < assignments.length; col++)
{
for(int row = 0; row < assignments[col].length; row++)
assignAvgArray[row] += assignments[row][col];
assignAvgArray[col] = (assignAvgArray[col]/5);
}
}
assignments.length is 5 so col can become 4.
assignAvgArray.length is 4. When you are giving the aassignAvgArray col=4 it will throw an arrayoutofboundException.
fix it ,and if you still have an error comment under my answer.

Categories