hi @sona11 - this is a very good problem for learning how to program.
There is no method in Java to do this, you need to write it. I want to help you but I am not going to give you the code, you will not learn that way.
int array []={1 2 3 4 5 6 7 8 9 10}
Your example array is an array of int
which is a primitive data type in Java, not an object like String
, List
, etc.
The substring()
in Java is used with the String
object which is why it will not work with an array or an int
.
Examples:
String s = "Jagged Array";
s.substring(7); // will return Array
s.substring(0, 6); // will return Jagged
The example you refer to can help.
Copy that example to your IDE and change the following lines:
Replace this;
Scanner scn = new Scanner(System.in);
//Taking the input from user
int r = scn.nextInt();
with this:
int r = 3;
We are just removing the user input from the code and hardcoding the number of rows, in this case we put 3
.
Then run it in debug. You can also change the value of r
each time you run to see what happens. This should help you understand what it is doing.
Pay special attention to the nested loop when you are stepping in debug.
int temp = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = temp++;
Once you understand that example you can start thinking about how to make it more flexible. I will try to help you with that if you want (but I won’t give you code).
What version of Java are you using? And what IDE, if you are using an IDE?
I hope this helps you in the learning process.