How to check index of integer array element in java? [duplicate] - java

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}

Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.

The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.

For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.

Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}

You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

Related

Is there a way to assign values into an Array with forEach?

I'm pretty new to programming and learned the forEach loop in Java. As far as I know it's a shorter version of the classic for loop. My question is, how can I save values into an array with forEach or is it read-only?
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
for (int i : arr) {
arr[i] = i;
}
But my array is [0,0,0,0,0]. (Of course it is, but can I modify it somehow?)
If not is there another way instead of the normal for-loop?
Short answer: no, there is no way.
Longer answer: With a for-each loop you lose the index information, i.e. within the loop you don't know if you are dealing with thefirst, the second or the hundredth element. You need the index to address the position to write to in the array. So with using only the for-each there is no way.
Mind: In your example the first loop just overwrites the array's elements with their indexes. You'll get arr = { 0, 1, 2, 3, 4 }.
The second loop only works, because it iterates over an arrays whose elements are their own indexes by chance–as you defined it that way before.
If your array for example was `arr = { 42, 101, -73, 0, 5 }' the first iteration would try to access the 43nd element of an array with only five elements, thus causing an exception.
You could create and increment your own index counter, but that's actually what the conventional for-loop does in a very convenient way.
conventional for loop:
for (int index = 0; index < arr.length; index++) {
var element = array[index];
use(element);
}
for-each loop:
for (int element : arr) {
// the current index is unknown here
use(element);
}

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].
The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?
public static int[] reverseIntArray(int[] array) {
int[] result = new int[10];
int j = array.length;
for (int i = 1; i < array.length; i++ ) {
result[i] = array[j];
j++;
}
return result;
}
how should the error be corrected?
what exactly is the error?
what effect the error would have?
You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.
There are a couple of issues with your code:
Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++
To solve array related problem you must know only about its storage in memory and its index.
In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.
NOTE: You must know that how to swap two numbers.
int[] arr={1,2,3,4};
int i=0;
int j=arr.length-1;
while(i<j)
{
//Swapping two numbers
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
You can also do the same using for loop.

Java Null Pointer with String Array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.

What is this algorithm doing?

I got a pseudocode:
Input: Array A with n (= length) >= 2
Output: x
x = 0;
for i = 1 to n do
for j = i+1 to n do
if x < |A[i] - A[j]| then
x = |A[i] - A[j]|;
end if
end for
end for
return x;
I have converted that to a real code to see better what it does:
public class Test
{
public static void main (String[] args)
{
int A[] = {1,2,3,4,5,6,7,8,9};
int x = 0;
for (int i = 1; i < A.length; i++)
{
for (int j = i + 1; j < A.length; j++)
{
if (x < Math.abs(A[i] - A[j]))
{
x = Math.abs(A[i] - A[j]);
}
}
}
System.out.println(x);
}
}
The output was 7 with the array in the code.
I have used another array (1 to 20) and the putput was 18.
Array 1-30, the output was 28.
The pattern seems clear, the algorithm gives you the antepenultimate / third from last array value. Or am I wrong?
I think the pseudo code tries to find the greater of the difference between any 2 elements within an array.
Your real code however, starts from 1 instead of 0 and therefore excludes the first element within this array.
I think pseudocode is trying to find the greatest difference between two numbers in an array. It should be the difference between the minimum and maximum value of the array.
I personally think this is a really poor algorithm since it is doing this task in O(n^2). You can find the min and maximum value of an array in O(n). and take the difference between those numbers and result will be the same. check the pseudocode
Input: Array A with n (= length) >= 2
min=A[0];max = A[0];
for i = 1 to n do
if min > A[i] then
min = A[i];
end if
if max < A[i] then
max = A[i]
end if
end for
return (max-min);
The code gives the biggest difference between any two elements in the array.
There are 2 nested loops, each running over each element of the array. The second loop starts at the element after the first loop's element, so that each possible pair is considered only once.
The variable x is the current maximum, initialized to 0. If x is less than the absolute value of the current pair's difference, then we have a new maximum and it is stored.
However, because you directly copied the pseudocode's starting index of 1, you are inadvertently skipping the first element of the array, with index 0. So your Java code is giving you the maximum difference without considering the first element.
If you have an array of values between 1 and n, you are skipping the 1 (in index 0) and the returned value is n - 2, which happens to be the third-to-last value in the array. If you had shuffled the values in the array as a different test case, then you would see that the returned value would have changed to n - 1 as now both 1 and n would be considered (as long as n itself wasn't in the first position).
In any case, you would need to set the index of the first element to 0 so that the first element is considered. Then {1,2,3,4,5,6,7,8,9} would yield 8 (or any other order of those same elements).
Assuming all positive integers, the algorithm in a nutshell finds the difference between the maximum and the minimum value in the array. However, it will not work correctly unless you initialize i to 0 in the for loop.
for (int i = 0; i < A.length; i++)

Java: How to find index of last element of partially initialized sorted array

Suppose I create an int array of size N. Then I fill up the array with sorted numbers until index x, where 0 <= x < N-1. How can I find the index x?
Here's one of the examples of the array: {0,1,2,3,4,0,0,0,0,0}, and here's how I generated the array:
int[] arr = new int[10];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Is there any Java syntax for this? I am specifically talking about Array not ArrayList.
====UPDATE====
Sorry for the confusion, the above array was just an example. Suppose the partially initialized array is given, such that we don't know how it was generated. Again, to be clear, the array can also be initialized as {0,0,0,1,2,6,7,0,0,0,0} where the last 0,0,0,0 part is the part from being uninitialized, whereas the first 0,0,0 is deliberately written by somebody else.
You should use Integer class and not int primitive data type. Read about more things you can do with Integer class
Integer arr[] = new Integer[10];
This is initialized to null for each element. Now you can add number to it.
public int indexOfArray(Integer [] arr) {
int i=0;
while(arr[i]!=null) {
i++;
}
return i;
}
You said your array is sorted. So, you can search for the biggest element into the array and then uses Arrays.asList(arr).indexOf(biggestElement);
int biggetsElement = arr[0];
for(int i=1; i < arr.length; i++){
if(arr[i] > biggestElement){
biggestElement = arr[i];
}
}
int index = Arrays.asList(arr).indexOf(biggestElement);
I'm not sure if it will work with int elements, if not you can use Integer elements instead.
Not possible as specified. What if the "sorted values" are all negative and end at -1, e.g.:
[-5,-4,-3,-2,-1, 0,0,0,0]
vs. "sorted values" that are all non-positive but end in 0 (spaces added to emphasize the end of the initial sorted numbers)
[-5,-4,-3,-2,-1,0, 0,0,0]
There's no way to tell afterwards which 0 is the "first" unsorted one.
Assuming you dont know what x is, and assuming that the only value of uninitialized elements is 0, and that all initialized elements cant have the value 0 (which is not true in your case), then you will just have to do a linear search for it -
int i=0;
while(arr[i]!=0) i++;
return i
Create for loop and put in it condition that will check if next element is sorted
Code:
int x
for(int i=0;i<arr.length;i++)
if(arr[i+1]-arr[i]!=1)
x=i;
You can use this :
int index = Arrays.binarySearch(theArray, 0);
Condition : the array must be sorted
edit
Use Integer :
Integer[] theArray = {0, 0, 0, 1, 2, 4, 7, null, null, null};
int index = Arrays.binarySearch(theArray, null);

Categories