Creating and Using arrays - java

I am new to the concept of arrays in java, and as part of an assignment, I am required to create a 10 row by 3 column integer array and populate it with a for loop. I have the following.
public class arrays{
int arr[][][] = new int [10][10][10];
for(int i=0;i<arr.length;++i)
{
for(int j=0;j<arr[i].length;++j)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
am I on the right track?

You are actually declaring a 3-dimensional array.
You should instead be declaring int[][] arr = new int[10][3];.
You can then assign values as follows: arr[i][j] = 42;
Note also that when instantiated, the initial values in the array are 0.

The way of creating array in java is simple and I see you know that but for your problem applicable array might be different. Try that one
int arr[][] = new int [10][3];
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
arr[i][j] = your_integer_value;
}
}

Related

How can I print all common numbers in three inputted user arrays?

int ar1, ar2, ar3;
System.out.print("Enter size of the 1st array: ");
//reading the number of elements from the that we want to enter
ar1 = sc.nextInt();
System.out.print("Enter value of the 1st array: ");
for (int i = 0; i < ar1; i++) {
array[i] = sc.nextInt();
}
System.out.println("Array1: ");
for (int i = 0; i < ar1; i++) {
System.out.println(array[i] + " ");
}
What can I add to print the common numbers in three inputted numbers in arrays?
first of all - arrays are primitive and quite a pain if it comes to using them. An alternative would be using ArrayList. But since you’re using arrays in this question, this would be an idea to solve the problem:
When your arrays are set up you can iterate through them to compare them. To do that you could declare 2 additional arrays:
int[] matchesA1A2 = new int[array1.length];
int[] matchesAll = new int[array1.length];
where machesA1A2 will contain the values that are both in array1 and array2. And matchesAll ALL the matching numbers.
Now just iterate through the first array comparing it with the second one to find which values match. Like that:
for (int i = 0; i<array1.length; i++){
for (int i2 = 0; i2<array2.length; i2++){
if (array1[i]==array2[i2]){
matchesA1A2[i] = array1[i];
}
}
}
The first two array are now compared. Now you can iterate through the third array comparing it witch the MATCHES of the array1 and array2 (which is the matchA1A2 array). Like this:
for (int i3 = 0; i3<array3.length; i3++){
for (int im = 0; im<matchesA1A2.length; im++){
if (array3[i3]==matchesA1A2[im]){
matchesAll[i3] = array3[i3];
}
}
}
If you println the matchesAll array you should see something, like this: [0, 0, 0, number, 0, 0, number, 0, 0…]
System.out.println(Arrays.toString(matchesAll));
Alle the “numbers” in the array are values that match in all three arrays.
Disclaimer: this is not the best way to write code, but I think because of the way it’s written it is easier for beginners to understand the concept of iterating.

How to set size of two dimensional ArrayList?

So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.

Adding integers to an int array

I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

I am trying to reverse a two dimensional array and keep getting a null exception

Here is my method that is suppose to reverse the array.
(Also, keep in mind that this method can receive a jagged array)
public static int[][] reverse(int[][]a){
int[][] rev = new int[a.length][];
int row = a.length;
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
for(int y=0; y< a[x].length;y++){
rev[row-1][col-1]= a[x][y];
col--;
}
row--;
}
return rev;
}// reverse method
I keep getting
Exception in thread "main" java.lang.NullPointerException
at Home.reverse(Home.java:259)
at Home.main(Home.java:56)
Java Result: 1
Here is my main that calls that method
int[][] two = {{1,2,3,4},{0,1,2},{9},{1,3,5,7}};
System.out.println("The size of array os " + ar.length);
System.out.println("The columns of array is " + ar[0].length);
int[][] rev;
//int[] b = concatenate(ar);
//int[] c = concatenate(two);
//int[][] rev = reverse(ar);
//for(int x=0;x<c.length;x++){System.out.println("worked" + c[x]);}
rev = reverse(two);
//for(int x = 0;x<rev.length;x++){
// for(int y = 0;y<rev[x].length;y++){
// System.out.print(rev[x][y]);
//}
//}
for(int x=0;x<rev.length;x++){
for(int y=0;y<rev[x].length;y++){
System.out.print(rev[x][y]);
}
}
}// main
So my question is really, where did I go wrong?
I traced my reverse method and it looks like it should be doing its job but apparently not.
Your array rev has not been initialized in its second coordinate. After your declaration int[][] rev = new int[a.length][], all your rev[i] are null objects (arrays are objects, even for primitive types). To avoid that, initialize with int[][] rev = new int[a.length][a[0].length] or with rev[i] = new int[a[i].length] or so, if the array is jagged.
When you say this line
int[][] rev = new int[a.length][];
You have created an array of length a.length of arrays, but the internal arrays are all null. So you are getting a NullPointerException on this line:
rev[row-1][col-1]= a[x][y];
You need to create your internal arrays inside the first for loop. This will satisfy your "jagged array" requirement.
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
rev[row-1] = new int[a[x].length]; // Add this to create differing lengths.
for(int y=0; y< a[x].length;y++){

Categories