Trying to display the last index of a item in array Java - java

I am trying to display the last index of an item in array, an example:
{6,4,7,3,11,4} Last index of 4 = 5
I have written this method so far:
public int lastIndexOf(int[] nums, int num) {
int found = 0;
for (int i = nums.length; i < 0 ; i--) {
if (nums[i] == num) {
return i;
}
}
return -1;
}
Why does this not work? I am under the impression that you need to start the for loop at the start of the arrays length and then work backwards. I want to be able to use a for loop to do this, I set up a condition if there are no occurrences of the number to return -1 but when I am running this code I always return -1 no matter what numbers I am putting in.
How would I solve this using a for loop?

Your for loop conditions are not correct. Should be
for (int i = nums.length-1; i >= 0 ; i--) {
The "i<0" from before prevented it from entering the loop.
But the "i = nums.length" would have given you an Index out of bounds error. Need to subtract by 1 because Arrays are 0 indexed

You can also turn the array into list and use List's lastIndexOf method so you don't have to implement yourself.
Arrays.asList(nums).lastIndexOf(num)
note that lastIndexOf return -1 if num is not found in nums

Related

Comparing all the characters beetween two strings(even if they contain numbers)in java

Ok so I currently have a String array which contains keycodes, and i want to check if the first element shares common specifications with the second , e.g. [012] has similar elements with [123]. I currently loop through the length of the first element, and then loop through the length of the second element, and compare those two like this:
If(A[1].charAt(j) == A[2].charAt[i]) c++; c is a counter to show how many
common elements the keycodes have. Here is the method i created
static boolean hasSimilarity(String[] A, int K, int i){
int c = 0;
for(int j = 0;j<K;j++){
for(int m = j;m<K;m++){
if(A[i].charAt(j) == A[i+1].charAt(m)) c++;
}
}
return c != 0;
}
And here is the execution of it in the Main class:
int max = -1;
findSimilar FS = new findSimilar();
for (int i = 0; i < sum.length -1; i++) {
boolean hasSimilar = FS.hasSimilarity(key,K,i);
if (!hasSimilar) {
int summ = sum[i] + sum[i + 1];
System.out.println(summ);
if (summ > max) {
max = summ;
}
}
}
When i run this, i get a java.lang.StringIndexOutOfBoundsException out of range: 0 . What am I doing wrong? Is there any better way to compare two keycodes in order to find similarities beetween them?
This error:
java.lang.StringIndexOutOfBoundsException out of range: 0
Can only occur if one of your strings is the blank string "".
You are attempting to get charAt(0) when there is no char 0 (ie first char).
——-
You would avoid this problem, and have a far more efficient algorithm, if you first collected the counts of each character then compared those, which would have time complexity O(n), whereas your algorithm is O(n2) (albeit that it seems your n - the length of your inputs - is small).

Why there is no error while executing IF statement in this algorithm?

I was repeating some previously passed Java topics and got curious about how exactly does an algorithm work?
This algorithm finds the maximum number in an array of ints and returns its index.
public static int findIndexOfMax(int[] numbers) {
int index = 0;
for (int i = 1; i < numbers.length; i++) { //i = 0 doesn't seem to change anything
if (numbers[i] > numbers[index]) { //numbers[1] doesn't exist and still no errors
index = i;
}
}
return index;
}
public static void main(String[] args) {
System.out.println(findIndexOfMax(new int[] {99})); //passing an array with a single element
}
Sounds stupid, but why there is no error occured in IF statement if I pass an array with a single element to the method? There we compare non-existent numbers[1] with another int (since the first iteration is for i=1), but we don't get ArrayIndexOutOfBounds exception. What's the reason of it?
If you pass an array with a single element, the loop's body will never execute. i is initialized with 1, and thus the condition i < numbers.length is always false.
The loop's body is skipped, and an index of 0 is returned.

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.

Returning the number of times a number appears in an Array?

So I'm doing a bunch of exercises, one of them asks me to write a method that is passed an array with each slot type int. This method should return the number of times 99 occurs in the array. Here's what I came up with on the fly:
public static int countNum(int[]x)
{
int count = 0;
for (int i = 0; i <= x.length;i++);
{
if (x[i] == 99)
count++;
}
return count;
}
All in all, I just need to write the method. Am I on the right track?
Well, there are two mistakes.
First: i < x.length; it should be like that or i <= x.length - 1; like that or you will get out of your array.
Second:
for (int i = 0; i <= x.length;i++)**;**
{
if (x[i] == 99)
count++;
}
You don't need ; or the next code will be out of for.
array.length returns length of an array and you don't want to iterate from 0 to length, but from 0 to length - 1.
Why? For example if an array is [1, 5] then:
array.length == 2, array[0] == 1, array[1] == 5 but array[2] throws java.lang.ArrayIndexOutOfBoundsException (because it tries to reach an element which is not in the array)
Remove the semicolon after the for statement:
for (int i = 0; i <= x.length;i++);
(a for loop executes statements which comes directly after it, and ";" ends a statement. The for(...) followed by ";" means that you have a loop which does nothing x.length times)

Array not looping correctly - Java

I have an array with 60 values, and when I click the next button, it will cycle through all of the values of my array in ascending order until the number 60, then it starts at number one again.
I also have a previous button, so I can go down values instead of going up. When I hit the previous button on the first array value [0], my app crashes and I am not sure why.
Here is my code:
public String nextFact() {
i++;
if(i >= facts.length) {
i = 0;
}
return facts[i];
}
public String previousFact() {
i--;
if(i < 0) {
i = facts.length;
}
return facts[i];
}
You are getting an ArrayIndexOutOfBoundsException when you change i to facts.length, because valid array indexes range from 0 through facts.length - 1. Set i to facts.length - 1.
if(i < 0) {
i = facts.length - 1;
}
Your wrapping-around code for greater than or equal to the length should be working fine.
Your array is of size array.length. So the last index will be array.length-1. In your previous function, you assign array.length to i. This is larger index than max index for array and therefore it crashes down. You must be getting am indexoutofbound error too.
You should replace that line with this:
i = facts.length - 1;

Categories