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++;
}
}
Related
My goal for this program is to create a 2D-array ratings whose size is specified by the first two arguments from the command line. args[0] would represent the number of rows r and arg[1] would represent the number of columns c. The next arguments that follow would all be used to fill in the array. So if the command-line argument was 3 2 5 2 3 3 4 1. I would hope that the array would be 3 rows by 2 columns. The value 5 would be in ratings[0][0], the value 2 would be in ratings[0][1], the value 3 would be in ratings[1][0], etc. After that, I want to compute the sum of each column. So column 0 would be 12 and column 1 would be 6 in this scenario.
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
int c = Integer.parseInt(args[1]);
int[][] ratings = new int[r][c];
int z = 2;
int y = 3;
int x = 0;
int counting = 0;
int sum = 0;
for (int rows = 0; rows < ratings.length; rows++ ) {
for (int column = 0; column < ratings[c].length; column++){
ratings[rows][column] = Integer.parseInt(args[z]);
sum += ratings[rows][column];
z++;
}
System.out.println(sum);
sum = 0;
}
//System.out.println(movieRating);
}
This is my attempt at summing the columns but this right now just sums 5 and 2, 3 and 3, 4 and 1. I want the columns not the rows to be summed but do not know how to fix it. Thank you
You seem to be adding the values to the 2D array correctly. What you're missing is an additional nested loop to print out the column totals:
for (int i = 0; i < ratings[c].length; i++) {
int colSum = 0;
for (int j = 0; j < ratings.length; j++) {
colSum += ratings[j][i];
}
System.out.println(colSum);
}
Add that where you currently have that //System.out.println(movieRating); line. Since you were adding the numbers to the array row-wise, you need to flip the for loops to be able to sum the columns.
Things you did right
You correctly initialized the ratings 2D-array with the values given on the command line. Let me re-write this below without your attempt at computing the columns' sum. Note that I renamed the variables so that the indices used in the for loop are single letter variable.
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
argIndex++;
}
}
}
Thing you didn't get right
The ratings array is filled row by row. In the code you posted, you compute in variable sum the sum of the elements inserted in the same row. This is the reason why it doesn't print the results you expected.
To compute the sum of each columns, I would recommend you create a new array in which to store this result. Integrating it with the code above:
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int[] columnSums = new int[columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
columnSums[c] += ratings[r][c];
argIndex++;
}
}
// array columnSums contains your results
}
I have changed your original code with a simpler version.
Let me know if you have problems understanding the solution.
public static void main(String[] args)
{
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int arrayLength = row * col; // use a single dimension array, for simplicity
int[] ratings = new int[arrayLength]; // the array size is based on the rows and columns
// add data to the 'ratings' array
// This is not actually needed because the conversion can be done directly when the columns are summed up
for(int i = 0; i < arrayLength; i++)
{
ratings[i] = Integer.parseInt(args[i + 2]);
}
// sum up the columns using the % operator
int[] result = new int[col];
for(int i = 0; i < arrayLength; i++)
{
result[i % col] += ratings[i];
}
// print result
for(int i = 0; i < result.length; i++)
{
System.out.println(String.format("Movie %d rating is %d", i, result[i]));
}
}
PS: you are missing the validation around the String to int conversion and checks around the correctness of the user input
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.
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;
}
//...
}
I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)
My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}