how to convert nested loop to 2D array - java

i would ask if there is some way to print some thing called (Star pattern)!
for(int x=1; x<=5; x++)
{
for(int y=1; y<=x; y++)
{
System.out.print("*");
}
System.out.println();
}
the output (i guess...)
*****
****
***
**
*
so...
could you tell me please, it is possible to print same with array 2d?
thank you for help!

Yes: it's possible. You have to crate an array of 5x5 and fill previously with stars and spaces. Then you have to create a function to print that array.

Did you mean creating and handling arrays that consist of arrays of different sizes? Then it might look, for example, like the following:
public class TestArray {
public static void main(String... args) {
// Create and fill the array we need
char[][] array = new char[5][]; // Create an array of 5 arrays
for (int i = 0; i < array.length; i++) {
array[i] = new char[i+1]; // Each item of the array is a new array of a new size
for (int j = 0; j < array[i].length; j++)
array[i][j] = '*'; // fill the new array with stars
}
// Print the contents of the array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) // Each item is an array
System.out.print(array[i][j]); // print its contents
System.out.println(); // new line
}
}

Related

How to create two dimensional grid with two-d. array?

This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}

ArrayIndexOutOfBoundsException while printing a 3D array in JAVA

I wrote the following code in JAVA.
package threed;
import java.util.Scanner;
public class Threed_Array {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int b1,b2,b3;
System.out.print("Enter the number of elements in 1st bracket->");
Scanner sc=new Scanner(System.in);
b1=sc.nextInt();
System.out.print("Enter the number of elements in 2nd bracket->");
b2=sc.nextInt();
System.out.print("Enter the number of elements in 3rd bracket->");
b3=sc.nextInt();
int threedarray[][][]=new int[b1][b2][b3];
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
}
}
I am getting ArrayIndexOutOfBoundsException for this code. This is showing in the line:
threedarray[i][j][k]=sc.nextInt();
Can anybody help me out where the error is occurring? Thank you.
You should always start at index 0, it is the index of the first element of your array:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
furthermore make the check with < not <=
With the last loop you access the array element n+1 where n is the size of that array. Thats the reason for the exception.
I'd say the conditions in your loops are not correct :
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
it should be :
for(int i=1; i<=b1; i++)
{
for(int j=1; j<=b2; j++)
{
for(int k=1; k<=b3; k++)
{
Also, you should start at 0 in each of them.
I think you want j and k in the 2 inside for loops instead of i. Also, arrays in Java start in index 0, so it should look like this:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
...
}
}
}
Arrays in Java are zero-based, try to iterate from 0 to b1-1:
for(int i=0; i<b1; i++)
{
for(int j=0; i<b2; j++)
{
for(int k=0; i<b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
[b1][b2][b3]
You create an array using the inputs b1,b2,b3
The array created has length of bx but subscripts from 0 to bx-1. Hence you must loop from 0 to bx-1
Indices start at 0, not 1. Start your three for loops at 0 and iterate to one less than the number provide:
for(int i = 0; i < b1; i++)
{
for(int j = 0; i < b2; j++)
{
for(int k = 0; i < b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
Apart from the array index problem (see Stefan Beike's answer), you could you an ArrayList.
This would avoid having to ask the user for the number of elements you want to have in your matrix.
Still if you want to keep primitive arrays, you could use System.arrayCopy to reallocate to a greater size array.
The problem here is that you are starting the loop from 1 till the b1,b2,b3 respectively. Array indexes start from 0 not from 1 and ends at the size of the array - 1. So to fix your code you need to modify the code to be the following:
for(int i = 0; i < b1; i++) {
for(int j = 0; j < b2; j++) {
for(int k = 0; k < b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
More generally if you don't know the length/size of the array you are looping on, you can make the loop more generally to be less than the array length. So it would be i < threedarray.length and j < threedarray[i].length and k < threedarray[i][j].length.
The key idea is that the array indexing starts from 0 and ends at its size/length - 1, so to get the last element you access array[array.length-1] and to access the first element you access array[0]
Hope this answers your question.

Converting 1-D String array to 2-D char array

I'm working on a program that requires me to take in a 1-D String array from a file and turn it into a 2-D array. Taking in the array from the file works fine, but I can't get the second part to work.
The code I'm working with is:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
The array is supposed to print in a grid format, but is printing downward.
Any help is appreciated, thanks.
Use print instead of println in inner loop and after each loop print a blank line with println.
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
Update:
Following is a program that convert String array to 2D char array.
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}
few suggestions,
replace char[][] array2 = new char [7][5]; with char[][] array2 = new char [array1.length][]; (where array1 holds your strings), so your 2d array will have as many rows as you have strings
your loop
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
....
}
change to
for (int i = 0; i < array2.length; i++)
{
for (int j = 0; j < array2[i].length; j++)
....
another thing is if you want your string printed in rows, use System.out.print, and whenever you finished inner loop, print out'\n' character
You are using println, which is why each character is printed on its own line. You must use print instead.
Note that your initialization with
new char [7][5];
doesn't work as you expect because the inner arrays will be overwritten. Use
new char[7][]
for the same result, but more clarity as to your intent. Here
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
you have apparently reversed the order of indices: you are iterating only through 5 outer arrays, but you have allocated 7. What you should do instead is check against the actual array length and not a hardcoded number. The inner array may be of any size, after all (it depends on the string length).
Have a look at the String.toCharArray()
If it is printing downwards then change
for (int i = 0; i < 7; i++) //row loop
{
for (int j = 0; j < 5; j++) //column loop
{
System.out.print(array2[i][j]);
}
System.out.println(); //add here
}
Have a look at
formatting
print vs println

How to get the 2D Array length

I create method to display element in the 2D array. but I can't specify the array length for each dimension. this is my code
public static void display2DArray(String[][] array){
for (int i = 1; i < array.length; i++) {
for (int j = 1; j < array.length; j++) {
System.out.println("Document "+i+ " Section "+j);
System.out.println(" "+array[i][j]);
}
System.out.println(" ");
}
}
Please help me.
Try this way
public static void display2DArray(String[][] array){
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.println("Document "+i+ " Section "+j);
System.out.println(" "+array[i][j]);
}
System.out.println(" ");
}
}
In Java, every intrinsic array object (i.e. Object[]) has the "length" property.
If you have an object of type Object[][], you can view it as (Object[])[], meaning an array of arrays.
So what you do is use index "i" to get an inner array and then an index "j" to get an element from the inner array. Namely:
Object[][] myArray;
for (int i = 0; i < myArray.length; ++i)
for (int j = 0; j < myArray[i].length; ++j)
{ /* do something with myArray[i][j] */ }
First of all, i and j should both default to 0. Second, change j to be array[0].length, and before have a check if array is empty, just return right away. An array can be represented as follows:
{{[0][0] [0][1] [0][2]},
{[1][0] [1][1] [1][2]},
{[2][0] [2][1] [2][2]}}
So to get the height, you just do array.length, but for width, you gotta get one of the interal arrays' lengths, so array[0].length will do

need assistance with homework

This is the assignment: Write a method that sorts the elements of a matrix with 2 dimensions. For example
sort({{1,4}{2,3}})
would return a matrix
{{1,2}{3,4}}.
I dont know what im doing wrong in my code cause the output i get is 3.0, 3.0, 4.0, 4.0.
This is what i have so far any help would be appreciated.
public static void main(String[] args) {
double[][] array = { {1, 4}, {2, 3} };
double[][] new_array = sort(array);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
System.out.print(new_array[i][j] + " ");
}
}
}
public static double[][] sort(double[][] array) {
double[] storage = new double[array.length];
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
storage[i] = array[i][j];
}
}
storage = bubSort(storage);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
array[i][j] = storage[i];
}
}
return array;
}
public static double[] bubSort(double[] list) {
boolean changed = true;
double temp;
do {
changed = false;
for (int j = 0; j < list.length -1; j++)
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
return list;
}
}
The main problem that you are experiencing is how you are copying the values from the 2d array into the 1d array. You are actually only copy two values into an array of length 2. The length of a 2d array is not the full m x n length.
I will give a small hint how you can go about copying from the 2d array into the 1d array, but it is up to you to figure out how to copy back from the 1d array into the 2d array. Also, how would you go about finding the full length of the array?
double[] storage = new double[4];//You should calculate this value
int k = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
storage[k++] = array[i][j];
}
}
Your bubble sort works fine, but then you are copying the values back wrong. Try printing the array storage after the sort and you will see that it is now correct.
You are overwriting your storage array you have it set to array[i]. Because it is in the for loop you are setting storage[0] = array[0][0] then setting storage[0] = array[0][1]. This causes you to only pick up the last number in that dimension of the array. Likewise, when you are reading them back out you are inserting the same number twice. Since 4 and 3 are the last two numbers in their respective dimensions this shows that you are sorting the array. You need a for loop for storage that is set < array.length and store your values inside that.

Categories