I'm having a problem with two dimensional array. I'm having a display like this:
1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
What basically I want is to display to display it as:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 ... etc
Here is my code:
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;}
}
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
System.out.print("");}
}
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
A part from #djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.
Do this way:-
int twoDm[][]= new int[5][7];
for(i=0;i<5;i++){
for(j=0;j<7;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println("");
}
I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.
From the initial question, as has been adequately explained by #djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:
System.out.println();
However, printing that immediately after the first print statement gives erroneous results. What gives?
1
2
...
n
This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!
Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println();
}
And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.
Just for the records, Java 8 provides a better alternative.
int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};
System.out.println(Stream.of(table)
.map(rowParts -> Stream.of(rowParts
.map(element -> ((Integer)element).toString())
.collect(Collectors.joining("\t")))
.collect(Collectors.joining("\n")));
More efficient and easy way to print the 2D array in a formatted way:
Try this:
public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}
Sample Output:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
You can creat a method that prints the matrix as a table :
Note: That does not work well on matrices with numbers with many digits and
non-square matrices.
public static void printMatrix(int size,int row,int[][] matrix){
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
for(int i = 1;i <= matrix[row].length;i++){
System.out.printf("| %4d ",matrix[row][i - 1]);
}
System.out.println("|");
if(row == size - 1){
// when we reach the last row,
// print bottom line "---------"
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
}
}
public static void main(String[] args){
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
// print the elements of each row:
int rowsLength = matrix.length;
for(int k = 0; k < rowsLength; k++){
printMatrix(rowsLength,k,matrix);
}
}
Output :
---------------------
| 1 | 2 | 3 | 4 |
---------------------
| 5 | 6 | 7 | 8 |
---------------------
| 9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | 16 |
---------------------
I created this method while practicing loops and arrays, I'd rather use:
System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));
Iliya,
Sorry for that.
you code is work. but its had some problem with Array row and columns
here i correct your code this work correctly, you can try this ..
public static void printMatrix(int size, int row, int[][] matrix) {
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
for (int i = 1; i <= matrix[row].length; i++) {
System.out.printf("| %4d ", matrix[row][i - 1]);
}
System.out.println("|");
if (row == size - 1) {
// when we reach the last row,
// print bottom line "---------"
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
}
}
public static void length(int[][] matrix) {
int rowsLength = matrix.length;
for (int k = 0; k < rowsLength; k++) {
printMatrix(rowsLength, k, matrix);
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
};
length(matrix);
}
and out put look like
----------------------
| 1 | 2 | 5 |
----------------------
| 3 | 4 | 6 |
----------------------
| 7 | 8 | 9 |
----------------------
Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.
int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // the trick is here, print a new line after iterating first row.
}
public class class1 {
public static void main(String[] args){
int[][] a={{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i< a.length; i++){
System.out.print("Row" + (i + 1) + ": ");
for (int j = 0; j < a[i].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
result:
Row1: 1 2 3
Row2: 4 5 6
This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.
public static void display(int x[][]) // So we allow the method to take as input Multidimensional arrays
{
//Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
for(int rreshti = 0; rreshti < x.length; rreshti++) // Loop for the rows
{
for(int kolona = 0; kolona < x[rreshti].length;kolona++) // Loop for the columns
{
System.out.print(x[rreshti][kolona] + "\t"); // the \t simply spaces out the elements for a clear view
}
System.out.println(); // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look
}
}
After you complete creating this method, you simply put this into your main method:
display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)
Source: enter link description here
PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.
For traversing through a 2D array, I think the following for loop can be used.
for(int a[]: twoDm)
{
System.out.println(Arrays.toString(a));
}
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 5 },
{ 3, 4, 6 },
{ 7, 8, 9 }
};
System.out.println(" ** Matrix ** ");
for (int rows = 0; rows < 3; rows++) {
System.out.println("\n");
for (int columns = 0; columns < matrix[rows].length; columns++) {
System.out.print(matrix[rows][columns] + "\t");
}
}
}
This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.
ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ
just get length by arr[0].length and problem solved
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[0].length; j++) {
System.out.print(test[i][j]);
}
System.out.println();
}
Related
my output is
4 4 8 7
3 3 3 5 6 3 3 4 5
when it should be
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
i need to use same method for all of arrays, summing up arrays of two matrices.
how can i do that when arrays are different length and how can i print output correctly?
public static void main(String[] args) {
int[][] m1 = { { 1, 2, 0 }, { 2, 3, 4 } };
int[][] m2 = { { 3, 2, 5 }, { 6, 4, 3 } };
int[][] m3 = { { 1, 1, 1, 1 }, { 3, 3, 2, 1 }, { 2, 2, 2, 2 } };
int[][] m4 = { { 2, 2, 2, 3 }, { 2, 3, 1, 0 }, { 1, 2, 3, 4 } };
printMatrixSum(m1, m2);
System.out.println();
printMatrixSum(m3, m4);
}
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i=0; i < 2; ++i) {
for(int j=0;j<3;j++) {
c[i][j]=x[i][j]+y[i][j];
System.out.print(c[i][j]+" ");
}
}System.out.println();
}
}
Your code is close to working. I made some changes below, and it now produces this output:
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
Here's the code:
1. private static void printMatrixSum(int[][] x, int[][] y) {
2. int[][] c = new int[x.length][x[0].length];
3. for (int i = 0; i < x.length; i++) {
4. for (int j = 0; j < x[0].length; j++) {
5. c[i][j] = x[i][j] + y[i][j];
6. System.out.print(c[i][j] + " ");
7. }
8. System.out.println();
9. }
10. }
Here are the edits I made:
line 2: change int c[][] to int[][] c – this is minor, but follows Java style
line 2: change new int[4][4] to use actual values for array length. The first dimension is just x.length, and the second is x[0].length. This will work correctly with different array inputs vs. hard-coding to "4".
line 3: change i < 2 condition to use the length of one of the input arrays; I chose x but it could be y (and of course this code assumes that x and y are matching dimensions)
line 3: change ++i to i++ – not sure why you were using pre-increment, but in my opinion that makes it harder to reason about loop behavior, and also the second loop (line 4) was already doing post-increment (j++) so I edited this one to make it both clearer as well as consistent with the rest of your code.
line 4: change j < 3 to be dynamic, similar to edit on line 3
line 8: move the println() here, so that a newline is printed after each row of the array is printed
Instead of printing it with fixed sizes ( like i < 2 and j <3 ), use the dimension of the array to make your function more reusable.
ii) Secondly, the println() should be outside the inner loop but inside the outer loop .
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i = 0; i < x.length; ++i) {
for (int j = 0; j < y[0].length; j++) {
c[i][j] = x[i][j] + y[i][j];
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
and this is the answer :
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
A couple suggestions.
Consider not writing a printMatrixSum method. Write a method to print a matrix. You may not always want to print a matrix after you compute the sum. Of course that means iterating over the matrix twice so it's ultimately going to be based on your requirements.
specify a width value to help nicely format the output.
And you don't need to index the matrix. Multi-dimensional arrays are simply arrays of other arrays. So you can use the enhanced forloop to first iterate the rows, and then the values in each row.
Here is an example.
int [][] data = {{203,2,3334,-22022, 23},{2,1,233, 42,33}};
matPrint(data, 7);
prints
203 2 3334 -22022 23
2 1 233 42 33
use the width to specify the largest value(including sign)
create a format for System.out.printf
then simply iterate the rows. and within each row, iterate the values.
public static void matPrint(int[][] m, int width) {
String fmt = "%" + width + "s";
for (int[] row : m) {
for (int col : row) {
System.out.printf(fmt, col);
}
System.out.println();
}
}
If you have a specific width that you want to use often you can overload the print method as follows. Then you can use the one argument version which invokes the two argument with the default width.
private static int DEFAULT_WIDTH = 4;
public static void matPrint(int[][] m) {
matPrint(m, DEFAULT_WIDTH);
}
And if you specify the field width as a negative value, it will left justify the output within each field.
This question already has answers here:
Problem with assigning an array to other array in Java
(4 answers)
Make copy of an array
(11 answers)
Closed 2 years ago.
I'm trying to make a project in which an array is sorted by different sorting algorithms. However, I have noticed that after one algorithm sorts the array and displays the value, the original array is also changed. How can I solve this?
public static void main(String[] args) {
int[] array = {20, 35, -15, 7, 55, 1, -2};
printArray(array);
boubleSort(array);
printArray(array);
}
The first function prints out the array in its unsorted form, the second one sorts the array and then prints the sorted array. The third line prints the original array (which should remain unsorted) as sorted. Why odes this occur and how can I change this?
public static void boubleSort(int[] array) {
System.out.println("Bouble Sort");
int [] arr = array;
for(int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex;i++) {
if(arr[i] < arr[i+1]) {
swap(arr,i, i+1);
}
}
}
printArray(arr);
}
public static void swap(int [] array, int i, int j) {
if (i == j) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void printArray(int [] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println();
}
Current output: Desired output:
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2
Bouble Sort
35 35
20 20
7 7
1 1
-2 -2
-15 -15
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2
Multiplication table for 2 only
This is my code:
public class nest
{
public static void main (String[] args)
{
for (int row=1; row<=5; row++)
{
for (int column=1; column<=10; column++)
{
System.out.print(row*++column +"\t");
}
System.out.println();
}
}
}
This is my target results:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
But I'm getting this:
2 4 6 8 10
4 8 12 16 20
6 12 18 24 30
8 16 24 32 40
10 20 30 40 50
Help me please I'm still learning Java.
The trick here is in being able to articulate a formula for the value in each cell given a row and column index. Assuming we count both row and column starting from zero, then the formula is:
(2 + 10*row + 2*column)
This formula says that, starting with an initial value of 2, we increase by 10 moving down a row, and we increase by 2 moving to the right of a column. This leads to the following code:
for (int row=0; row < 5; ++row) {
for (int column=0; column < 5; column++) {
System.out.print((2 + 10*row + 2*column) + "\t");
}
System.out.println();
}
Demo
To make it simple you can do something like this:
public class A{
public static void main(String[] args){
int k=2;
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
System.out.print(k+"\t");
k=k+2;
}
System.out.println();
}
}
}
Similar to the above one. A simple one.
public static void main(String[] args) {
int tableOf = 2;
int currIter = tableOf;
for(int i = 1; i <= 5 ; i++) {
currIter = tableOf * i;
for(int j = 1; j <= 5 ; j++) {
System.out.print((currIter * j) + "\t");
}
System.out.println();
}
}
You can achieve your results by using an extra variable.
public class nest
{
public static void main (String[] args)
{ int table= 0;
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
table+=2;
System.out.print(table +"\t");
}
System.out.println();
}
}
}
the loops can be used to define rows and columns for printing table . hope it helped you a little.
You could also try (assuming you're using Java 8+), a formula based on breaking lines every five elements using a lambda and a ternary we can do so in a single statement. Generate a range of 1 to 25, multiply each value in the range by 2, and then print it (and if it isn't a multiple of 5 a tab, otherwise a newline). Like,
IntStream.rangeClosed(1, 25).map(i -> i * 2)
.forEachOrdered(i -> System.out.print(i + ((i % 5 != 0) ? "\t" : "\n")));
Your java code is great! It appears that you're just having a little bit of math logic problems.
Lets take a look at the following:
1 2 3 4 5
1
2
3
4
5
These are your rows and columns as you itterate through them in your loops.
2 4 6 8 10
Should be your first line which it is!
12 14 16 18 20
Should be your second line. Well lets take a look at your equation.
row*++column
++column means column + 1 = 2
1 * 2 is 2
we want 12
If we keep the range of the loops within 5 its much simpler.
public class nest
{
public static void main (String[] args)
{
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
System.out.print(logic math stuff +"\t");
}
System.out.println();
}
}
}
Looking at the expected output the numbers are just 1 - 25 * 2
Lets try to print 1 - 25 first.
Column itterates 1 - 5 so the first row is just column.
System.out.print(column + "\t");
1 2 3 4 5
Easy enough. So now on the second row we need 6 7 8 9 10.
Column is still 1 - 5 but row is now 2
The first number is supposed to be 6 so how do we get there?
row = 2
column = 1
Our column width is 5 so every itteration of row we have to add 5 * (row-1).
System.out.print((column + 5 * (row-1)) + "\t");
This prints 1 - 25 in 5 rows
Now double it!
System.out.print((column + 5 * (row-1)) * 2 + "\t");
im trying to create a matrix from a file, the file is like this:
Where my first line has the size of the matrix= 10 x 9
And in the other lines, we have 15 values distributed aleatory.
3 5
4 5 6
12 34 12 12 8
34 23
12 34 34 10 89
With the info size i will define my matriz. I use this method for read:
public static void read(){
String line= "";
int i = 0;
try {
while((line = bf.readLine()) != null){
if (i == 0){
//Call method that get the size and create my global matriz
}else{
String[] list = line.split(" ");
//I need help here, for insert correctly in the array
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How i can do for insert orderly in the matrix? My matrix should be like:
4 5 6 12 34
12 12 8 34 23
12 34 34 10 89
Any idea?
This is one way to do it:
String input = "3 5\n" +
"4 5 6\n" +
"12 34 12 12 8\n" +
"34 23\n" +
"12 34 34 10 89\n";
Scanner in = new Scanner(input);
final int rows = in.nextInt();
final int cols = in.nextInt();
int[][] matrix = new int[rows][cols];
int row = 0, col = 0;
for (int i = 0; i < rows * cols; i++) {
matrix[row][col] = in.nextInt();
if (++col == cols) {
row++;
col = 0;
}
}
System.out.println(Arrays.deepToString(matrix));
Output:
[[4, 5, 6, 12, 34], [12, 12, 8, 34, 23], [12, 34, 34, 10, 89]]
It is not necessarily the best way to do it, but I wanted to show the manual increment logic of col and row, where row is incremented when col rolls over.
Using answer by sebenalern, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = in.nextInt();
Using answer by Paul, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows * cols; i++)
matrix[i / 5][i % 5] = in.nextInt();
All 3 versions rely on the Scanner to simply provide all the values in a sequence, regardless of how they were put together on lines.
If you don't want to use Scanner (e.g. because it is slow), and read the input line-by-line, then values on a line, the 1st version would be easier to use. Otherwise the 3rd is the shortest, and the 2nd version is the most straightforward.
Just a hint - I'll leave your homework to you - :
In this case it would be pretty simple to maintain a counter of all values that have been read so far, and map each of these counter-values to a matrix-value like this:
0 = (0 , 0)
1 = (1 , 0)
...
5 = (0 , 1)
6 = (1 , 1)
...
Using something like this:
int row = counter / rowLength;
int col = counter % rowLength;
In your case:
matrix[counter/5][counter%5] = someValue;
public static void applicationB(int A, int B) {
int number = 1;
for (int row = 0; row < A; row++) {
for (int col = 0; col < B; col++) {
int output = number + row++;
System.out.printf("% 4d", output);
}
// does it skip because of this?
System.out.println("");
}
}
It outputs with A = 20, B = 5
1 2 3 4 5
7 8 9 10 11
13 14 15 16 17
19 20 21 22 23
The correct output should be
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
I cannot figure out how to get it to stop skipping 6, 12, and 18.
Am I just doing this a horrible way? or am I on the right track?
You are incrementing row in two places. Also, it would be easier to just have one loop, and output a line break every B elements (you can use i % B to test for this).
I would suggest the following approach. Iterate over the values you want to print out, from 1 to the maximum value (A). Then, print a newline whenever the remainder of value divided by the number of columns (B) is zero.
for (int value = 1; value <= A; value++) {
System.out.printf("% 4d", value);
if (value % B == 0) {
System.out.println("");
}
}