java get the number of array values - java

I already have the following code
public class Qn3
{
static BigDecimal[] accbal= new BigDecimal[20];
private static Integer[] accnums = new Integer[5];
public static void main(String[] args)
{
int count;
accnums = {1,2} //i cant add this line of code as well, what is wrong?
while(accnums.length < 5)
{
count = accnums.number_of_filled_up_indexes
//this is not actual code i know
//do this as the number of values in the array are less than 5
break;
}
//do this as number of values in the array are more than 5
}
}
I must use this code there is no changing this is a requirment, so please dont suggest to use arraylist and such (i am aware of other array types and methods)
The problem is that as I have already declared that accnums must contain only 5 values, that is predefined.
I am trying to perform a check whether the ones that are not null and if all are null. To do this I have tried this but this is giving me 5 p(pre-defined integer array value not what I want).

public static void main(String[] args)
{
int count = 0;
accnums = new Integer[] {1,2,null,null,null};
for (int index = 0; index < accnums.length; index++)
{
if(accnums[index] != null)
{
count++;
}
}
System.out.println("You have used " + count + " slots);
}

Try this...
accnums[0] = new Integer(1);
accnums[1] = new Integer(2);
Both the below will work if done during Declaration and Initializing time of and array.
Integer[] arr = new Integer[]{1,2,3};
Integer[] arr = {1,2,3}
But when you just declare the array as
Integer[] arr = new Integer[3]; // Still array holds no Object Reference Variable
then later initialize it this way...
arr = new Integer{1,2,3,}; // At this time it hold the ORV
Array are always initialized whether used at class or method scope, so for an int array all the values will be set to default as 0, and for Integer it will be null, as its an Wrapper object.
Eg:
Integer[] arr = new Integer[5];
arr[0] = 1;
arr[1] = 2;
System.out.println(arr.length);
for (Integer i : arr){
if (i!=null){
count++;
}
}
System.out.println("Total Index with Non Null Count :"+count);
}

accnums[0] = 1;
accnums[1] = 2;
final int count = accnums.length
- Collections.frequency(Arrays.asList(accnums), null);
System.out.println("You have used " + count + " slots");
or, if you really must do it manually...
int count;
for (final Integer val : accnums) {
if (val != null) {
++count;
}
}

Related

How to print additional arrays? [duplicate]

I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

Convert a string into a multidimensional arrays with different lengths

I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!

How to get a certain array element's key?

I'm pretty new to java, and I'm trying to create a simple method that sorts inputted numbers, either ascending or descending. However, there's a problem that I can't put in repeated values. Is there a way to get the key of a certain item of an array??
My code:
import java.io.Console;
public class TestSort {
public static void main(String args[]) {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
System.out.println("TESTSORT.java");
System.out.println("-------------");
System.out.println("Type in a set of numbers here:");
String in = c.readLine();
System.out.println("(A)scending or (D)escending");
String ad = c.readLine();
boolean d = false;
if(ad.equals("a")) d = false;
else if(ad.equals("d")) d = true;
else {
System.out.println("Invalid Input.");
System.exit(1);
}
String[] in2 = in.split(" ");
int[] x = new int[in2.length];
int count1 = 0;
for(String val : in2)
x[count1++] = Integer.parseInt(val);
int[] a = new int[x.length];
int count = 0;
for(int y : x) {
for(int z : x) {
// if index of y equals index of z continue
if(z < y) count++;
}
a[count] = y;
count = 0;
}
if(d) {
int[] arr3 = new int[a.length];
int length = a.length;
for(int b : a) arr3[--length] = b;
for(int b : arr3) System.out.println(b);
} else
for(int b : a)
System.out.println(b);
}
}
This program just counts up the number of other numbers smaller than itself, but not including itself. However, it doesn't differentiate itself from other numbers with the same value.
Help would be appreciated.
Thanks.
To get the index of a certain value for an array you will have to loop through the array. However if there is multiple entries with the same value this approach wouldn't work (without modification)
int indexVal = -1;
int inputValue; // This is your input vlaue you are trying to find
for(int i = 0; i < array.length ; i++)
{
if (array[i] == inputValue)
{
indexVal = i;
break;
}
}
You may also want to look at Array.sort for built in array sorrting
If you want an index you should not be using for each loops. You will have to use a regular for loop to get at an index in the array.
A SortedSet is perfect for this. As a set, it does not allow duplicate values, and it is sorted automatically for you!
Just add your elements to the set, e.g:
SortedSet<Integer> set = new SortedSet<Integer>();
for(String value : in2.split(" ")){
set.add(Integer.parseInt(value));
}
To reverse the order of the set do something like this:
SortedSet<Integer> descending = set.descendingSet();
You can iterate through sets just like arrays too:
for(Integer i : set){
//Do something
}
Good luck!

How to increase the size of an array in Java?

I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

Multi-Dimension length array reflection java

How do I find the length of a multi-dimensional array with reflection on java?
There is no such thing as "length" for multi-dimensional array; it may not be rectangular. I'm guessing you're talking about the number of dimensions. You need to descend into it iteratively and count.
public int getDimensionCount(Object array) {
int count = 0;
Class arrayClass = array.getClass();
while ( arrayClass.isArray() ) {
count++;
arrayClass = arrayClass.getComponentType();
}
return count;
}
Java arrays have lengths per instance, not all arrays in the same dimension have to have equals lengths. That said, you can get the lengths of instances in the.
Dimensions can be counted by the number of '[' in their name, this is quicker than descending the type hierarchy. The following code:
int[][][] ary = {{{0},{1}}};
Class cls = ary.getClass();
boolean isAry = cls.isArray();
String clsName = cls.getName();
System.out.println("is array=" + isAry);
System.out.println("name=" + clsName);
int nrDims = 1 + clsName.lastIndexOf('[');
System.out.println("nrDims=" + nrDims);
Object orly = ary;
for (int n = 0; n < nrDims; n++) {
int len = Array.getLength(orly);
System.out.println("dim[" + n + "]=" + len);
if (0 < len) {
orly = Array.get(orly, 0);
}
}
gives the following output:
is array=true
name=[[[I
nrDims=3
dim[0]=1
dim[1]=2
dim[2]=1
Class clazz = Class.forName("ReflectionTest");
Method m = clazz.getDeclaredMethod("getArray");
Object o1 = m.invoke(o, arg);
int array[][] = (int[][])o1;
System.out.println("Array length: " + array.length);
System.out.println("Array length: " + array[0].length);
Use java.lang.reflect.Array.getLength(obj).
If you like me were trying to get the number of dimensions and the size of them then:
private static int[] getDimentionsOf(final Object expectedArray) {
if (!expectedArray.getClass().isArray()) {
return new int[0];
}
final int dimensionSize = Array.getLength(expectedArray);
final int[] innerDimensions =
(expectedArray.getClass().getComponentType().isArray())
? getDimentionsOf(Array.get(expectedArray, 0))
: new int[0];
final int lenghtPlusOne = innerDimensions.length + 1;
final int[] newDimensions = new int[lenghtPlusOne];
System.arraycopy(innerDimensions, 0, newDimensions, 1, innerDimensions.length);
newDimensions[0] = dimensionSize;
return newDimensions;
}

Categories

Resources