read 2d array into triangle - java

I want to read the following into a 2d jagged array:
3
7 4
2 4 6
8 5 9 3
I need to increase the column size on every input. I'm not exactly sure how to do it.
My code is as follows:
int col = 1;
int[][] values = new int[rows][col];
for(int i = 0; i < values.length; i++){
for(int j = 1; j < col; j++)
{
values[i][j] = kb.nextInt();
col++;
}
}

This should do it.
int[][] values = new int[rows][];
for(int i = 0; i < values.length; i++)
{
values[i] = new int[i+1];
for(int j = 0; j < values[i].length; j++)
{
values[i][j] = kb.nextInt();
}
}
Basically, you start by defining how many rows your 2d array should have.
In the for loop, you define the 1d array for each row with its length.

Sample
// don't fix the second dimension
int[][] values = new int[rows][];
for(i = 0; i < rows;i ++){
//column size increases for every line input
values[i] = new int[i+1];
for(j = 0; j < values[i].length; j++) {
values[i][j] = kb.nextInt();
}
}
In Java, arrays do not have to be strictly rectangular. The variable values is a rows-element array of references to int arrays. Here, values[0] is a 1-element int array, values[1] is a 2-element int array, etc.

Related

How can I fill two-dimensional arrayList with one dimensional?

I have a problem that, whenever I try to fill two dimensional arrayList (5x5) with one dimensional, I get index out of bounds exceptions. I guess that's because the square Array doesn't have index 0 value yet, but I don't know how to fix it.
ArrayList<Character> c = new ArrayList<>();
// Copy character by character into arraylist
for (int i = 0; i < finalArray.length(); i++) {
c.add(i, finalArray.charAt(i));
}
ArrayList<ArrayList<Character>> square = new ArrayList<>();
//square.add(new ArrayList<>());
int k = 0;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
square.get(j).add(i, c.get(k));
k++;
}
}
Add a “row” List to the outer List before the inner loop. You are also using the wrong index for square.
int k = 0;
for(int i = 0; i < 4; i++){
square.add(new ArrayList<>()); // Initialize the row
for(int j = 0; j < 4; j++){
square.get(i).add(c.get(k++)); // get(i) not get(j)!
}
}
Note the other simplifications too.
It would be clearer to do this:
int k = 0;
for(int i = 0; i < 4; i++){
List<Character> row = new ArrayList<>();
square.add(row);
for(int j = 0; j < 4; j++){
row.add(c.get(k++));
}
}

Sort Array with two loops Implementation

I am new with Java.
I try to do one of my assignment, but i can not figure out why my result still can not sort.
I have a prompt value(argument) 20 10 30 60 55, and i want to sort it.
I wrote two loops, and converted prompt value (which is string) to Integer.
Result: ( It is not sorted)
20
10
30
60
55
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at question2.SortedArray.main(SortedArray.java:29)
This is the code i wrote:
int temp = 0;
int array[] = null;
int array2[];
for(int i=0; i<args.length; i++){
int a = Integer.parseInt(args[i]);
array = new int[a];
for(int j=0; j<args.length; j++){
int b = Integer.parseInt(args[i]);
array2 = new int[b];
if(array[i]>array2[j])
temp = array2[j];
array2[j] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < array.length; i++)
{
System.out.println(args[i].toString());
}
I could understand this code i fould online below
int tempVar;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j])
{
tempVar = numbers [j ];
numbers [j]= numbers [i];
numbers [i] = tempVar;
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
First, convert the String array of args into an int array of values. Then sort and display values. You've been sorting arrays (sized by your array int value), then printing the arguments (which you didn't sort). So, something like
int[] values = new int[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = Integer.parseInt(args[i]);
}
int temp = 0;
for (int i = 0; i < values.length - 1; i++) {
for (int j = i + 1; j < values.length; j++) {
if (values[i] > values[j]) {
temp = values[j];
values[j] = values[i];
values[i] = temp;
}
}
}
System.out.println(Arrays.toString(values));
You need to initialize your array to hold your prompt values
int [] yourArray = {2,3,4 5,};
You don't need a second array to sort the values just a temporary int to hold the value that is being moved.
The statements below if needs to be enclose with { } otherwise all it will do is run to the first semicolon and then get out of the if.
Basically what the code you pasted in the second part is checking if element at the value i is greater than the value at element j. If the value is greater it swaps j with i.
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j]) //if element at i is greater than element a j
{
tempVar = numbers [j ]; //store the number at element j in temp
numbers [j]= numbers [i];// set the number at element i to element j
numbers [i] = tempVar;// set the number at temp to element
}
} // does this for each element until no element i greater than j
}
Get the integers to an array at first.
int[] yourArray = { 20, 10, 30, 60, 55 };
for (int i = 0; i < yourArray.length; i++) {
for (int j = 0; j < yourArray.length - 1; j++) {
// swap
if (yourArray[i] < yourArray[j]) {
int temp = yourArray[i];
yourArray[i] = yourArray[j];
yourArray[j] = temp;
}
}
}
for (int i : yourArray)
System.out.println(i);
Output
10
20
30
55
60

convert a String array to a 2d array

I have a String array like this
3
1 5 5
2 -2 -3
15 -100 20
how can i convert this to a 2d array
1 5 5
2 -2 -3
15 -100 20
3 is the size of 2d
public static class convert(String[] lines){
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j < n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
Sin,
You have a couple of Off-by-one errors.
Try this:
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j-1][i] = Integer.parseInt(currentLine[i]);
}
}
Please let me know if you have any questions!
Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 0.
Change:
for (int j = 1; j < n; j++) {
to
for (int j = 0; j < n; j++) {
Also, it seems you want a method to do the conversion, not a class so you should remove this from your method signature and put void since you aren't returning anything from the method.
Change:
public static class convert(String[] lines)
To:
public static void convert(String[] lines)
Also, you should use a different variable to iterate through the string array to make things more cleaner. Since you are trying to use j, you can do that to. Instead of initializing j to 1, you initialize it to 0 as I've said and use j+1 as the index for accessing the lines array.
Here is how your code could look like:
public static void convert(String[] lines)
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 0, k = 1; j < n; j++) {
String[] currentLine = lines[j + 1].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}

Creating and initialising a 2D Array in Java

I haven't used 2D Arrays before so apologies for any 'obvious statements'.
I want to create a 2D Array for a 15 by 20 'table' and want the following to be applied:
I want each row to be a separate Array.
I want each row to have random 0's and 1's generated
The code I have created creates the 15 x 20 table but not sure if each row is an Array and can't figure out how to put random 0's and 1's. Help would be appreciated! Thanks!
for (int i=0; i < ar.length; i++) {
for (int j=0; j < ar[i].length; j++) {
ar[i][j] = 0;
System.out.print(" " + ar[i][j]);
}
System.out.println("");
}
Like this?
int cols = 15;
int rows = 20;
Random rand = new Random();
int[][] myArray = new int[rows][cols];
for (int i=0; i < myArray.length; i++) {
for (int j=0; j < myArray[i].length; j++) {
myArray[i][j] = rand.nextInt(2);
System.out.print(" " + myArray[i][j]);
}
System.out.println("");
}
Read more here
Use nextInt method.
myArray[i][j] = rand.nextInt(2); // we are using 2 cause nextInt generates random number between 0 to 2 exclusive.

Java 2d char array [duplicate]

This question already has answers here:
Converting 1-D String array to 2-D char array
(4 answers)
Closed 9 years ago.
Good day everyone, for the past couple of days I have been working on converting a 1D string array to a 2D char array. My 1D array works fine(zero issues) but when I convert to the 2D char array it only prints out the first row. Below is my code. Any feedback is appreciated. Thanks!
for(int i = 0; i < array1.length; i++) //prints out array
{
System.out.println("1d " + number[i]); //prints the line from the file
}
final int ROWS = 7;
final int COLS = 5;
char[][] 2darray = new char [ROWS][COLS];
for (int i = 0; i < array.length; i++)
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(2darray[row][col]);
}
System.out.println();
}
You cannot have variables start with a number in Java. I suggest changing your variables accordingly and trying it out.
char[][] array2 = new char [ROWS][COLS];
for (int i = 0; i < array.length(); i++)
{
array2[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(array2[row][col]);
}
System.out.println();
}
See Comments
for(int i = 0; i < array1.length; i++) //prints out array
{
// Why did you use number ?
System.out.println("1d " + array1[i]); //prints the line from the file
}
// You don't need these now.
// final int ROWS = 7;
// final int COLS = 5;
// This will initialize 2darray of size as required according to length of array1
char[][] 2darray = new char [array1.length][];
for (int i = 0; i < array1.length; i++) // What is `array`?
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < 2darray.length; row++) // Use actual size of 2darray row
{
for (int col = 0; col < 2darray[i].length; col++) // use actual size of 2darray column
{
System.out.print(2darray[row][col]);
}
System.out.println();
}

Categories

Resources