0

I am really new in Java. I have a question about put a set of array as 2d array. I really don't know how to do this with given array.This is my program

public static void main(String args[]){

    int arr[][]= new int[5][5];
     int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};


     int numberIndex=0;

    for(int i=0; i < arr.length; i++){
        arr[i] = new int[i+1];

        for(int j=0; j<arr[i].length; j++){
            arr[i][j] = number[numberIndex];

            System.out.println(numberIndex);
            numberIndex++;
        }
    }


}

Result is similar to this site, but it has to make by given array number Site

I understand the program below:( but i really don't know how to make it as array.)

public class RightAngledTriangleNumbers {
//void main
    public static void main (String[] args)
    {
        //declare int
        int i,j,n=1;
        //for loops
        for(i=1;i<=5;i++)
        {
            for(j=1;j<=i;j++)
            {
                System.out.print(n+" ");
                n++;
            }
        System.out.print("n");
        }
    }

}

Jake Huang
  • 140
  • 1
  • 12
  • 2
    You're on the right track. Define a separate `numberIndex` variable, _outside_ the loops, that will be used as an index into `number`. Set `arr[i][j] = number[numberIndex]` and then increase `numberIndex`. The use of `numberIndex` will similar to how `n` is used in the second program, except that `numberIndex` will be used as an index into the `number` array, instead of being the actual number. – ajb Oct 23 '14 at 22:22
  • Code Updated. But it is not running as right-triangle. – Jake Huang Oct 23 '14 at 22:41
  • google this => convert 2d array to 1d array in Java – Kick Buttowski Oct 23 '14 at 22:41
  • Sorry, i only allow to use array and for loops – Jake Huang Oct 23 '14 at 22:43
  • The link is what i did, but it won't work in my program. I am not sure if i did wrong somewhere. – Jake Huang Oct 23 '14 at 22:45
  • @JakeHuang You're not clear on what you needed. Are you trying to create a 2-D array, or print out the values as a right triangle, or both at the same time? The second example prints out the values, almost. The last line, `System.out.print("n")`, should be `System.out.println()` to go to the next line. If you want to make your first program print things out while it's setting up the array, use the same kinds of `print` calls. But I'm not clear on why you want to do both. – ajb Oct 23 '14 at 22:48
  • I am sorry for confusing. I want to make the result as right-triangle as second program by using given array like this `int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};` – Jake Huang Oct 23 '14 at 22:51
  • Should i change my title? – Jake Huang Oct 23 '14 at 22:53
  • Could anyone tell me where i did it wrong? – Jake Huang Oct 23 '14 at 23:49

0 Answers0