I have to create a 2D jagged array with a random number of rows (5-10) with each row having a random length (5-10). I filled the jagged array with random numbers. It should look something like this:
2 4 1 5 3 8 6 3
2 5 8 9 7 4 3 5 6
6 7 9 3 5
2 6 7 8 4 5 3 6 7
1 4 2 2 1
This is my current createArray method
public static int [][] createArray(){
int row = (int)(Math.random()*5)+5;
int column = (int)(Math.random()*5)+5;
int[][]array = new int[row][];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
//Fill the matrix with random numbers
array[i][j] = (int)(Math.random()*10);
}}
return array;
}//End createArray method
However, this just randomizes the rows and columns and doesn't create a jagged array. Can anyone help lead me in the right direction? Thanks a lot!
As #DoubleDouble stated, your code throws a NullPointerException.
It looks like you want something like this:
public static int [][] createArray(){
int row = (int)(Math.random()*5)+5;
//int column = (int)(Math.random()*5)+5; //not needed
int[][] array = new int[row][];
for(int i = 0; i < array.length; i++){
int column = (int)(Math.random()*5)+5; //create your random column count on each iteration
array[i] = new int[column]; //Initialize with each random column count
for(int j = 0; j < array[i].length; j++){
//Fill the matrix with random numbers
array[i][j] = (int)(Math.random()*10);
}
}
return array;
}//End createArray method
Of course it will produce different results each time it runs, but here is a sample of what it will output:
1 2 5 4 3 9 2 7 9
4 1 4 2 2 6
9 5 7 8 7 8 4 2
8 3 8 7 9 4 0
0 2 1 4 9 3 7 8
4 0 3 8 3
1 3 8 9 9 8
package JavaPrograms;
import java.util.Random;
public class jaggedarr
{
public static void main(String[] args) {
int a[][] = new int[3][];
Random r = new Random();
a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[3];
for (int[] a1 : a)
{
for (int j = 0; j < a1.length; j++)
{
a1[j] = r.nextInt(20);
}
}
for(int i[] : a)
{
for(int j : i)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}
Related
My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]
I am having trouble storing a matrix from a text file into a 2D array. Every time I run the following code, it executes with no errors but nothing is printed out in the console. Any help would be greatly appreciated. My code is shown below:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input1.txt"));
String [][] array = new String [9][9];
try{
for(int i = 0; i > array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.next();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}
Also this is the content of the text file I am reading in:
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
3 4 5 2 8 6 1 7 9
The problem is with your first loop, also it's better to use nextInt() when the content of "input1.txt" is int
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input1.txt"));
int [][] array = new int [9][9];
try{
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.nextInt();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}
you have error in first for loop
Scanner sc = new Scanner(new File("input1.txt"));
String [][] array = new String [9][9];
try{
for(int i = 0; i < array.length; i++) { // your error was here. you wrote int i = 0 i > array.length; i++
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.next();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}
Just before I begin to annoy you, I am a Java beginner and my main issue up to date is two- ord more-dimensional arrays.
Let me represent my problem:
The task in the study was: you have an sorted array, then you type the number of how many searching operations(let them named by N) the Programm should do.
Due to this you type N x 2 different values a and b, a should be smaller than b.
The Programm should search in the sorted array for intervalls containing your a and b and print these intervalls out.
For example:
The array to search for looks like this:
[1, 3, 5, 7, 9]
then the user types in the number of operations, for example 3. Following to this the a and b couples:
3 6
2 9
1 5
The output of the programm should be according to these a and b couples:
3 7
1 9
1 5
I tried to master this exercise but as mentioned above I have problems with multidimensional arrays. At the following you can see my code and I just want tipps or specific informations about arrays to understand how they're working.
And i improved it:
import java.util.*;
public class Blatt9{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
boolean check1 = false;
int N = s.nextInt();
int[] array = new int[N];
for(int i = 0; i < array.length; i++){
array[i] = s.nextInt();
}
for(int j = 0; j < array.length; j++){
for(int k = j+1; j < array.length -1; j++){
if(array[j] < array[k]){
check1 = true;
}
else{
check1 = false;
}
}
}
if(check1){
System.out.println("nicht aufsteigend sortiert");
}
else{
System.out.println("korrekt");
}
//Beginn der eigentlichen Aufgabe
int abfragen = s.nextInt(); // Anzahl der Abfragen
int[][] arr = new int[abfragen][2]; //um die abfragen zu speichern
int a = 0;
int b = 0;
for(int i = 0; i < abfragen; i++){
a = s.nextInt();
b = s.nextInt();
if(a>b){
System.out.println("Zahl 1 muss kleiner Zahl 2 sein");
break;
}
arr[i][0] = a;
arr[i][1] = b;
}
int intervall1 = 0;
int intervall2 = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < arr.length; j++){
if(array[i] <= a){
intervall1 = a;
}
if(array[i]>= b){
intervall2 = b;
}
}
System.out.print(intervall1 + " " + intervall2);
System.out.println();
}
}
}
The output now is:
input:
5
1 3 5 7 9
korrekt
3
3 6
2 9
1 5
begin of output:
1 0
1 0
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
So if I have one int[3][3] temp1 and an int[3][3] temp2, both filled up, how would I combine them to make one temp1and2[6][3]? What I'm trying to do is splice a grid array, where x is the array to be spliced and y is the column I want to remove. I tried
public static int[][] splice(int[][] x, int y){
int[][] temp1 = new int[y][x[0].length];
for(int i = 0; i < y; i++){
for(int j = 0; j < x[0].length; j++)
temp1[i][j] = x[i][j];
}
int[][] temp2 = new int[x.length-y][x[0].length];
for(int i = y; i < x.length; i++){
for(int j = 0; j < x[0].length; j++)
temp2[i][j] = x[i][j];
}
int[][] temp1and2 = new int[temp1.length + temp2.length][x[0].length];
System.arraycopy(temp1, 0, temp1and2, 0, temp1.length);
System.arraycopy(temp2, 0, temp1and2, temp1.length, temp2.length);
return temp1and2;
}
but that didn't work. I am getting the error:
java.lang.ArrayIndexOutOfBoundsException: 2 on the temp2[i][j] = x[i][j]; line.
So for example, temp1 and temp2 would both be would be:
1 2 3
4 5 6
7 8 9
and the combined would be:
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
This is how i would do it by hand
//returns a new 2D array with temp1 stacked on top of temp2 or
// null if the arrays aren't the correct dimensions
public int[][] stackArrays(int[][] temp1, int[][] temp2)
{
int [][] temp1n2 = null;
if(temp1.length != 0 && temp1.length == temp2.length
&& temp1[0].length == temp2[0].length)
{
//create the new array to hold both
temp1n2 = new int[temp1.length + temp2.length][temp1[0].length];
for(int i = 0; i < temp1.length; i++)
{
for(int j = 0; j < temp1[i].length; j++)
{
temp1n2[i][j] = temp1[i][j];
temp1n2[i + temp1.length][j] = temp2[i][j];
}
}
}
return temp1n2;
}
The result of stackArrays(allZero2DArray, allOnes2DArray) gives the following 2D array:
000
000
000
111
111
111
I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.
What I need is that if I have a matrix like this:
1 2 3
4 5 6
7 8 9
The elements of the diagonal are = 1 5 9
What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:
1 2 3
4 5 6
7 8 9
sum = 2+3+6 = 11
I would appreciate it if someone could help me to fix my problem.
this my code:
public int calculate(){
int sum = 0;
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row == col){
sum = sum + row+1 ;
}
}
}
System.out.println("the sum is: " + sum );
return sum;
}
public static void main(String[] args) {
int[][] ma = new int[2][2];
Question2 q2 = new Question2(2, 2, ma);
q2.fill();
q2.calculate();
}
the output is:
2 1
2 1
the sum is: 3
You want col to go through all elements, being always bigger than the diagonal.
Therefore try:
int sum = 0;
for(int i = 0 ; i < a.length ; ++i) {
for(int j = i + 1 ; j < a[i].length ; ++j) {
sum += a[i][j];
}
}