I wanted to ask a question of code that has grated ja, I have the following code, I am going through a 10x5 array to fill it with number 1, to 49 for a primitive and the function that is responsible for making ticket gives me very rare errors. Index On Bound in theory the function would not have to go out of the way but I do not know what to do if someone can hit me.
// It is this part that gives me an error, I have a fly
int ,c=0;
int m[][]= new int[10][5];
for (int i=0;i<m.length;i++) {
for (int x=0;x<m.length;x++,i++) {
m[x][i]=c;
}
}
// This part of code I only have to check if the data output
// does them correctly
for(int i=0;i<m[0].length;i++) {
for(int x=0;x<m.length;x++) {
System.out.print(" "+m[i][x]+" ");
}
System.out.println(" ");
}
}
El error que me da es siguiente:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at provas/provas.main.main(main.java:11)
Looks like you want to fill given array with numbers from 1 to 49. So you have to pay attention on:
int[][] arr = new int[10][5] creates an int array with 10 rows and 5 columns
arr.length gives you a total rows amount
arr[0].length given you a total columns amount at row 0 (each row could have different length).
public static int[][] fillArray(int[][] arr) {
int i = 1;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = i++;
return arr;
}
And finally to print an array:
public static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++)
System.out.format("%3d", arr[row][col]);
System.out.println();
}
}
You original method could be like this:
int[][] arr = fillArray(new int[10][5]);
printArray(arr);
Related
My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.
So i'm a beginner;
The task is to convert a given string into the array, the string always has the first characcter as the amount of rows and the second character as the amount of columns.
My problem is to solve how to move the rest of the string 's' into the 2D array from the 1D array.
Thanks in advance!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int arows = Integer.parseInt(s[0]);
int acols = Integer.parseInt(s[1]);
int[][] cells = new int[arows][acols];
for (int col = 0; col < acols; col++){
for (int row = 0; row <= arows;row++){
cells[row][col] = Integer.parseInt(s[2]);
}
}
}
}
You need to implement a counter for your for-loops to iterate through the input string. What you are doing right now is to fill your 2D-Array with the third element of your string.
One solution would be to just declare a variable i = 2, and increment it for each pass of the inner for-loop.
int i = 2
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
Edit: removed <= in row loop, changed the initial value of the index to 2
This is the solution, you have to put another iterator, and initialize it to 2, so to skip the first two elements of s[]
int i = 2;
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
I am trying to make an array that outputs a pattern depending on how many rows and columns I give it for the input and I receive an error when it gets to the third method. I understand that the array begins at index zero and if i input (0 0) for the matrix it's out of bounds but i have no idea how to fix the problem. Thank you for the help!
Here is my code for the first class:
public class Transpose {
public static int [][] createPatterned2DArray(int rows, int cols)
{
int [][] table = new int [rows] [cols];
for (int numRows = 0; numRows < table.length; numRows++){
for (int numCols = 0; numCols < table[0].length; numCols++){
table [numRows][numCols] = 10 + rows*(numRows +1) + numCols;
}
}
return table;
}
public static void print2DArray (int[][] matrix)
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.printf("%-4d",matrix[row][col]);
}
System.out.println();
}
}
public static void print2DArrayTransposed(int [][] matrix)
{
for (int row = 0; row < matrix[0].length; row++)
{
for (int col = 0; col < matrix.length; col++)
{
//try {
// if (matrix[0] == 0) {
// System.out.println(matrix[0][0]);
// throw new Exception();
System.out.printf("%-4d",matrix [col][row]);
// }
//catch (Exception e){
// System.out.print(e);
}
System.out.println();
}
}
}
Here is the second class:
import java.util.*;
public class TestTranspose extends Transpose {
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
int rows = scan.nextInt();
int cols = scan.nextInt();
int [][] table = createPatterned2DArray(rows,cols);
print2DArray(table);
System.out.println();
print2DArrayTransposed(table);
System.out.println();
}
}
This is the error that I am getting and its driving me insane!
I can't seem to wrap my head around how to throw an exception or to make the output display nothing when i enter an input of (0 0) for the arrays. How can I correct this line of code that does not let me output an array of (0 0)?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Transpose.print2DArrayTransposed(Transpose.java:32)
at TestTranspose.main(TestTranspose.java:13)
You can't safely do matrix[0].length without first ensuring that matrix.length != 0. In your other two methods, the outer loops on row take care of this.
But in print2DArrayTransposed it's your outer loop that's trying to do row < matrix[0].length; there's nothing to stop it trying to do that even when matrix.length == 0. You can address this in one of two ways: add this early bail-out at the top of print2DArrayTransposed:
if (matrix.length == 0)
return;
or change your outer loop on 'row' to:
for (row = 0; matrix.length > 0 && row < matrix[0].length; ++row)
Take a look at this line of code in the Transpose.print2DArrayTransposed() method:
for (int row = 0; row < matrix[0].length; row++)
You are trying to access the first element of matrix, but there is no element because the length is zero.
A 0x0 array is valid, so no need to disallow creating the array in the first place. My suggestion would just be to simply check at the start of the method if the length of matrix is zero, and if so, just return because there is nothing to print (or print some helpful message instead).
public static void print2DArrayTransposed(final int[][] matrix) {
if (matrix.length == 0) {
return;
}
//...
}
This is a school project. It is to display the info from the array into a tubular format with totals on the right side and across the bottom for each row and column. It does all the totals except one row. I can't find where the problem is. Can anyone help?!
import java.util.Scanner;
//program uses class Scanner
public class Ex6_20
{
//method begins java application
public static void main(String[] args)
{
//create Scanner to obtain imput
Scanner input = new Scanner(System.in);
int monthySales=0; //varible to hold mothly sales
int productNum; //varible to hold product number
int salesNum=0; //varible to hold saleperson number
int totalSales=0; //varible to hold total sales
int []totalProduct = {0,0,0,0,0};//build array to hold total product
int []salesTotal = {0,0,0,0,0};//build array to hold total salesperson
// Build array to hold sales information by salesperson and poduct
int[][]sales = {{2000,1500,500,800,0},
{500,2200,600,1000,0},
{1000,2000,300,2100,0},
{2500,4000,400,3000,0},
{300,3200,500,2300,0},
{0,0,0,0}};
//figure total by product
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
totalProduct[column] += sales[row][column];
}//end for
//figure total by salesperson
for(int column = 0; column < sales.length; column++)
{
for(int row = 0; row < sales[column].length; row++)
salesTotal[row] += sales[column][row];
}//end for
//fill totals for product
for(int i = 0; i < 5; i++)
{
sales[i][4] = totalProduct[i];
}//end for
//fill totals for salesperson
for(int i = 0; i < 4; i++)
{
sales[5][i] = salesTotal[i];
}//end for
// print info from array in table format
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
System.out.print(sales[row][column]+"\t");
System.out.println();
}//end for
} //end main method
} //end class
There are a few problems:
If you swap the variable names "row" and "column" in "figure total by salesperson" you'll notice that you are actually doing exactly the same calculation as "figure total by product", just with misleading variable names. (You're using column as the row index, and vice versa.) As of now, both totalProduct and salesTotal contain identical values, which is not right.
That is the main problem.
Also, when you display sales total and product totals, they are actually swapped. I suspect this is because you mean to have a total product per row with totalProduct[row] += ... and a total sales per column with salesTotal[column] += ..., but maybe the names are just swapped and the row/column indices are ok.
I'd actually recommend removing the extra sum fields from the sales array so all of the rows have the same number of columns and using hard-coded array bounds to start with, in order to make it more obvious what's happening until you get the sums correct. Then once the sums come up right, you can go back and make it work more generally. Otherwise, you may keep getting ArrayIndexOutOfBounds exceptions without it being obvious why, which is how I suspect you ended up with this solution so far.
For example, you could start with something very straightforward like this, then go back and make it a lot nicer and more general so it can work with different array sizes:
int[][] table = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
int[] rowSums = new int[3];
int[] colSums = new int[5];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
rowSums[i] += table[i][j];
colSums[j] += table[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(table[i][j]);
System.out.print('\t');
}
System.out.println(rowSums[i]);
}
for (int j = 0; j < 5; j++) {
System.out.print(colSums[j]);
System.out.print('\t');
}
System.out.println();
I would like to first apologize if my question is worded badly. I have an exam tmmrw and the prof gave a sample final exam for us to practice with. He unfortunately isn't responding with the solutions on the forum so I am trying to provide solutions on there. I seem to be stuck on this question. I have to write a method that accepts and NxM array filled with integer values as a parameter. The method is to return an (N+1)x(M+1) array which contains the contents of the original array in the first N rows and M columns plus a count of items greater than or equal to zero in each row/column at the end of that row/column and put the value -1 in the bottom right corner. for example.
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
I seem to be able to copy the array yet I am puzzled as to how I can enter the values in the outer parts of the new array. Here is what I have so far.
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
First off you are initializing the new array wrong it should be
int[][] matrix = new int[arr.length+1][arr[0].length+1];
You don't want it to be the same length you want it to be the length +1. Also in your for loops you want to go by the length of arr not matrix since thats what you're taking from. While putting the values into the new N+1xM+1 array, increment the value of the corresponding last element in that row and column by 1 if it is >=0.
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
After putting all the values back into the new N+1xM+1 array you should now take the values in the n sized and m sized arrays and put them into the corresponding slot in the N+1xM+1 array. After that just put the -1 in the bottom right slow manually.
matrix[matrix.length-1][matrix[0].length-1]=-1;
In your process2D method start off by creating an array with the correct size which has 1 more row and 1 more column than the original:
int[][] matrix = new int[arr.length+1][arr[0].length+1];
Then to populate the matrix array you do like you were doing before, but you need to take care not to reference an index of the arr array that is out of bounds. Because your matrix index is bigger than arr. If you are populating the new indexes then you can just use random numbers.
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
So here is the full method process2D:
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length+1][arr[0].length+1];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
}
}
// assign the corner -1 here
return matrix;
}