I am trying to create a program that allows me to create a grid using a 2D array and nested for loop.
The problem is that when I run the program numbers do not form a table, they instead are printed out in a vertical column.
I first set up the array with 3 rows, each having arbitrary values. I then use a nested for loop where the first loop is meant to create the rows for which the loop will run, and the second loop is meant to create the columns.
package nestedLoops;
public class Trial_1 {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3, 4, 5},
{1, 2, 3, 4},
{1, 2, 3, 4, 5}
};
for(int i=0; i<grid.length; i++ ) {
for(int j=0; j<grid[i].length; j++) {
System.out.println(grid[i][j]);
}
}
}
}
However when I run the above code I get this output:
1
2
3
4
5
1
2
3
4
1
2
3
4
5
I think you need something like that:
for (int[] ints : grid) {
for (int anInt : ints) {
System.out.print(anInt);
}
System.out.println();
}
In the second loop you need to print 'anInt' and to wrap a line you need to add a line break between the loops.
You have to advance the output to the new line after printing each row.
For that, you need to a System.out.println(); statement after the nested loop.
In the nested loop you need to use System.out.print(); (not println) for printing the numbers of every row. And you also need to add a delimiter (white space, tabulation, etc.) between the numbers inside the row, or else they will get jumbled like that 12345.
int[][] grid = {{1, 2, 3}, {11, 22, 33}};
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + "\t");
}
System.out.println();
}
Output
1 2 3
11 22 33
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.
I am working on an HW assignment that asks to write a method called count that determines the number of times a target value appears in an array. For example, if your array is [2, 3, 3, 3, 4, 6, 7, 8, 8, 9], the value 8 appears twice and the number 4 appears once. You should know that the method has two parameters and one return value. The code works but the problem that I am having is when I print the statement "The value x[i] appears count(x,x[i]) times" it repeats the same statement when it should only print the statement for each value. I need help on making it so it will only print the statement as long as the value is different from the one before it if it is the same as the value before it the code should skip and move on to the next value in the array until it prints everything.
import java.util.Arrays;
public class Q7 {
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i++) {
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
counter++;
}
}
return counter;
}
}
Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.
in the case of your example (because the array is sorted), you can just
change
for (int i = 0; i < x.length; i++)
to
for (int i = 0; i < x.length; i = i + count(x, x[i]))
It will skip duplicate items.
You must somehow remember for which values you have already printed the message. there are several ways to do this. For example, you could sort your array and only output the message if you hit a value you didn't have yet while iterating. Another simple approach would be to add the elements to a set to get unique values of the array. Example with a set:
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
Set<Integer> set = new HashSet<>();
for (int i = 0; i < x.length; i++) {
if(set.add(x[i])){
System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
}
}
}
I have two arrays and I am trying to assign the values of one array, i.e. arrayOne[0] should be equal to the corresponding index in arrayTwo[0].
I am trying to do this using a forloop so that it loops through the the index of one array assigning the values sequentially.
so far I have:
for (int a =0; a< arrayOne.length; ++) {
// this sets the an int that loops through the value of the arrays(both arrayOne and arrayTwo are the same length)
I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.
I know this is a very basic question but I am, as my name suggests, struggling to learn coding.
I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.
There are many ways to copy arrays. But since you specifically asked for a for loop solution, just create a new array of the same size and use a for loop as shown to index them.
int [] a = {1,2,3,4,5,6,7};
int [] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i]; // this copies element a[i] to b[i] where i is the index.
}
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
Prints
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
This question already has answers here:
ArrayIndexOutOfBounds on enhanced for loop
(2 answers)
Closed 6 years ago.
I'm going through an example on Code Wars. Essentially, taking a number, finding the multiples of 3 and 5 and adding these together. Assuming the number is 10, we'll have 3,5,6,9.
I am at the point where I want to add the multiples together (the foreach loop at the bottom) but I keep getting an OutOfBoundsException. I don't understand how it is reaching index 5! Can someone please explain this to me?
I've seen a few examples of this error on here but can't checking through these I've not been able to resolve the issue, sorry.
package Test;
import java.util.ArrayList;
import java.util.List;
public class MultiplesOf3And5 {
public static void main(String[] args) {
int number = 10;
int total = 0;
List<Integer> multiples = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if (i % 3 == 0) {
System.out.println(i + " is a multiple of 3");
multiples.add(i);
} else if (i % 5 == 0) {
System.out.println(i + " is a multiple of 5");
multiples.add(i);
}
}
for (int j : multiples){
System.out.println(multiples.get(j));
System.out.println(multiples.toString());
total += multiples.get(j);
}
System.out.println(total);
}
}
for-each loop iterates the values of your List multiples, you used each value of the List as index by accident. Fix it as below:
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString());
total += j;
}
The output is:
3 is a multiple of 3
5 is a multiple of 5
6 is a multiple of 3
9 is a multiple of 3
3
[3, 5, 6, 9]
5
[3, 5, 6, 9]
6
[3, 5, 6, 9]
9
[3, 5, 6, 9]
23
System.out.println(j);
You are trying to get the jth object out of the list, but the you are iterating over the values not the index.
your ArrayList have = 3,6,9(factor of 3) & 5(factor of 5)
so total 4-value reside into ArrayList.
now you are trying to get value from ArrayList not based upon index like 0,1,2,3...
but you are fetching value from ArryList likewise, multiples.get(3), .get(6)... etc.
that's why you get error, like ArrayIndexOutOfBoundException.
Better to follow this way,
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString()); // not required but you want then remain it is likewise... or else remove this line
total += j;
}
Your error is occurring because your for loop is assigning the actual values of your array list. Try this:
for(int j = 0, j < multiples.size(), j++) {
System.out.println(multiples.get(j))
}
The var j holds the current value of your iteration, not the current index of the iteration.
This should be enough :
for (int j : multiples) {
System.out.println(multiples.toString());
total += j;
}
For my summer Java class, I'm working on a program that detects whether the elements in an array are a magic square. I'm not entirely sure how to properly iterate through the array to be able to calculate the total of the separate columns and rows to determine if the array is a magic square. We were given the code for the sum of the down diagonal, but I'm unsure how to approach the up diagonal, rows and columns. Here is a snippet of my code so far.
public class MagicSqaure
{
public static void main(String[] args)
{
int[][] array =
{
{2, 7, 6},
{9, 5, 1},
{4, 3, 8}
};
public static int getSumOfDownDiagonal(int[][] array)
{
int total = 0;
for (int i = 0; i < array.length; i++)
{
total += array[i][i];
}
return total;
}
Since it is a class, I can only provide help on how to accomplish traversing through the rows, columns and up diagonal, but providing **no code at all*. It's up to you to do the right implementation, otherwise you're not learning but copying/pasting/becoming a zombie coder.
To traverse each row, go through the elements of your array of arrays like this:
total += array[i][j];
Where i won't change but j changes.
To traverse each column, go through the elements of your array of arrays like this:
total += array[i][j];
Where i changes but j won't change.
To traverse the up diagonal, go through the elements of your array of arrays like this:
total += array[i][j];
Where i starts at the last possible index of the array of arrays and j starts at the first index of the array of arrays.
Whenever I need to derive equations for certain behaviors, I just write a few of the answers out manually then look for patterns. First let's assume this is how we access items in the array:
column
0 1 2
--------
0 | 2 7 6
row 1 | 9 5 1
2 | 4 3 8
(Using array[column][row])
Now let's get the indices for the columns:
column 0 = {2, 9, 4} = array[0][0], array[0][1], array[0][2]
column 1 = {7, 5, 3} = array[1][0], array[1][1], array[1][2]
And here are the rows:
row 0 = {2, 7, 6} = array[0][0], array[1][0], array[2][0]
row 1 = {9, 5, 1} = array[0][1], array[1][1], array[2][1]
And here's the other diagonal:
3x3 array = {4, 5, 6} = array[0][2], array[1][1], array[2][0]
4x4 array = array[0][3], array[1][2], array[2][1], array[3][0]
Notice any patterns? For the diagonal, we start at array[0][array.length - 1] and end at array[array.length - 1][0]. This means our loop would be as follows:
int total = 0;
for (int i = 0; i < array.length; i++)
{
total += array[i][array.length - 1 - i];
}
return total;
And to sum a column, it'd be:
int total = 0;
for (int i = 0; i < array.length; i++)
{
total += array[column_index][i];
}
return total;
And for rows:
int total = 0;
for (int i = 0; i < array.length; i++)
{
total += array[i][row_index];
}
return total;
EDIT: In response to downvotes and comments, I have modified the magic square code to work with row-major conventions. Oh wait, no I didn't since the code would be identical. Anyway, this is how you do it.