How to find the index of an element in an int array?

前端 未结 19 1387
南方客
南方客 2020-11-27 02:56

How can I find an index of a certain value in a Java array of type int?

I tried using Arrays.binarySearch on my unsorted array, it only som

19条回答
  •  被撕碎了的回忆
    2020-11-27 03:18

    In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.

    import java.util.Random;
    public class scratch {
        public static void main(String[] args){
            Random rnd = new Random();
            int randomIntegers[] = new int[20];
            double smallest = randomIntegers[0];
            int location = 0;
    
            for(int i = 0; i < randomIntegers.length; i++){             // fills array with random integers
                randomIntegers[i] = rnd.nextInt(99) + 1;
                System.out.println(" --" + i + "-- " + randomIntegers[i]);
            }
    
            for (int i = 0; i < randomIntegers.length; i++){            // get the location of smallest number in the array 
                if(randomIntegers[i] < smallest){
                    smallest = randomIntegers[i];                 
                }
            }
    
            for (int i = 0; i < randomIntegers.length; i++){                
                if(randomIntegers[i] == smallest){                      //break the loop when array location value == 
                    break;
                }
                location ++;
            }
            System.out.println("location: " + location + "\nsmallest: " + smallest);
        }
    }
    

    Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.

提交回复
热议问题