Length of an Array - java

Ok so, you can create an array(EX: String[]) that holds a single value for each index by using length(), but that cannot be used for an array(EX: String[][]) that holds multiple values.
How would I pull the amount of indexes in the second mentioned array?

For 2d array
String[][] a=new String[4][5];
a.length // will give row count
a[0].length // will give column count of row 0 you can change the index for other columns
Demo

The same way:
String[][] aa = // ...
System.out.println("aa has " + aa.length + " indices");
for(int i = 0 ; i < aa.length ; ++i) {
System.out.println("aa[" + i + "] has " + aa[i].length + " indices");
}

To get the length of the array, you can do the same as you used to.
But if you want to get the amount of String objects, you can do something like this:
Stream.of(array).mapToInt(a -> a.length).sum()

Related

How to print Java array values with one particular id?

I am new to Java. I have one array with values but I want to print the values with id that mean{"id":1} My array with values are
int[] arr={1,2,3,4,5};
I want to print output values like below
{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}
Is it possible in Java?
You can iterate over the array and just
int[] arr = {1,2,3,4,5};
for(int a : arr){
System.out.println("{id:" + a + "}");
}
Where "a" is a short life variable that takes the value of each element in the array "arr"
This way you can print {id:1} with this short code.
You can do as follow :
int[] arr = {1,2,3,4,5};
String id = "\"id\"";
for(int i = 0 ; i <=arr.length; i++){
System.out.println("{"+id+": " + arr[i] + "}");
}
Here's the way to do it in recent Java versions (8 or higher)
System.out.println(
Arrays.stream(arr) // stream over int array
.mapToObj(i -> "{\"i\":" + i + "}") // convert int to custom String
.collect(Collectors.joining(", ")) // join Strings using a comma
) // print the big string

Storing a random number in an array with a loop

I need to store a random number into an array and then be able to compare the array sums at a later time. So far I have this:
public class Die {
private int dieValue = 0;
private Random randomNumbers = new Random();
public Die() {
}
public void rollDie() {
dieValue = randomNumbers.nextInt(6*1);
}
public void displayDie() {
int[] die = new int[3];
for(int counter = 0; counter<die.length; counter++ ) {
rollDie();
die[counter] = dieValue;
}
System.out.print("Your Dies are: " + die[1] + " and " + die[2] + " and "
+ die[3]);
dieValue = die[1] + die[2] + die[3];
}
This gives me an error saying the array index is out of bounds, and i'm not sure how to properly code this.. any tips would be great!
In Java, arrays start at index 0, so an array of size 3 (like you've made) will have indices 0,1,2. The out of bounds is because you're trying to used indices 1,2,3 (3 does not exist).
Also, you're saying that you need to access the values at a later time, so you should probably declare the array outwith the method, so that it persists after the method finishes (just now, due to the scope of the variable, it will disappear after displayDie() finishes.)
When you are trying to access the first value stored in an array the index should be 0, in you code above you try to access the 3 values as die[1], die[2], and die[3], but you need to be accessing them as die[0], die[1], and die[2].
Indexes for the die array in the displayDie() method are off, array index in Java starts from 0. First value will be die[0] instead of die[1].
Last line you have
dieValue = die[1] + die[2] + die[3];
and suppose to be
dieValue = die[0] + die[1] + die[2];
because there's not die[3] that's why you get the error
What you can do and will be better to loop the array
for(int i=0; i< die.length; i++){
dieValue +=die[i];
}

Storing contents of a webtable in a 2d matrix

I am trying to get the contents of a webtable using selenium and then store the contents in a 2d matrix.
Below is my code :
//Locate the webtable
WebElement reportTable = driver.findElement(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]"));
int rowCount = driver.findElements(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr")).size(); //Get number of rows
System.out.println("Number of rows : " +rowCount);
String[][] reportMatrix = new String[rowCount-1][]; //Declare new 2d String array
//rowCount-1 because the first row is header which i don't need to store
int mainColCount = 0;
for(int i=2;i<=rowCount;i++) //Start count from second row, and loop till last row
{
int columnCount = driver.findElements(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td")).size(); //Get number of columns
System.out.println("Number of columns : " +columnCount);
mainColCount = columnCount;
for(int j=1;j<=columnCount;j++) //Start count from first column and loop till last column
{
String text = driver.findElement(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td["+j+"]/div")).getText(); //Get cell contents
System.out.println(i + " " + j + " " + text);
reportMatrix[i-2][j-1] = text; //Store cell contents in 2d array, adjust index values accordingly
}
}
//Print contents of 2d matrix
for(int i=0;i<rowCount-1;i++)
{
for(int j=0;j<mainColCount;j++)
{
System.out.print(reportMatrix[i][j] + " ");
}
System.out.println();
}
This gives me a Null Pointer Exception at "reportMatrix[i-2][j-1] = text".
I don't understand what I am doing wrong. Do I have to give even the second index when I declare the 2d array ?
Thanks in advance.
Unless you're a student who is studying multi-dimensional arrays, or you are otherwise constrained by an API you're required to use, just avoid arrays. You'll stay saner longer :)
If you HAVE to use a 2D array, it's wise to remember that you are not actually creating a matrix. You are creating a 1D array, and each element of this array is another 1D array. When you think of it that way, it becomes clear that you definitely have to initialize the "columns" arrays as well as the "rows" array.
This line:
String[][] reportMatrix = new String[rowCount-1][];
will initialize report matrix to have rowCount - 1 rows, and null for each and every set of columns.
Inside your first loop, after you have identified the number of columns, you want to do something like so:
reportMatrix[i] = new String[columnCount];
for(int j=1;j<=columnCount;j++) ...
This will allow you to have different number of columns in each row, if necessary.
Then, in your print loop, you should use the array lengths to print out the rows and columns. Remember to subtract 1 from the length attribute, since the this represents the number of elements in the array, and we almost always use zero-indexed for loops.
//Print contents of 2d matrix
for(int i=0; i < reportMatrix.length - 1; i++)
{
for(int j=0; j < reportMatrix[i].length - 1; j++)
{
System.out.print(reportMatrix[i][j] + " ");
}
System.out.println();
}

Java code, array/matrix component

I have this 3x1 array/matrix in java. How can i use any one of the single components of the array. Lets say i want to
r = Math.pow(second row component,2) + Math.pow(third row component,2)
What is the calling code for the components?
Thanks
Use a foreach to iterate through the array, and then add Math.Pow index by index
double[] myArray = { 1.2, 16.5, 20.0 }
double r = 0;
for(double d : myArray)
{
r+= Math.pow(d,2);
}
If by components you mean elements, then the syntax is as follows:
int[] numbers = {1,2,3,4,5};
int num = numbers[0];
System.out.println("Number: " + num);
// Outputs Number: 1
Extra Reading
You should read the documentation. This contains all of the information you need to use the array type in Java.
If you want to access an element of an array, apend the index of the element in brackets:
r = Math.pow(second row component,2) + Math.pow(third row component,2)
becomes
r = Math.pow(arrayVariable[1],2) + Math.pow(arrayVariable[2],2)
Remember, array indexes are base zero.

ArrayList of int array in java

I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}
You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);
Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.
List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.

Categories