确定java数组中数字的位置

时间:2015-09-07 16:03:14

标签: java arrays

我正在处理一个程序,该程序的随机数在1到100之间。提示用户输入一个数字,然后程序必须查看该值是否在数组中。我假设只要用户输入1到100之间的数字,该数字就会在数组中。如果用户输入的数字在数组中,我需要输出数字在数组中的位置。如何确定数字在随机生成数字数组中的位置?

import java.util.*;
public class Lab1
{
public static void main(String args[])
{
    Scanner input = new Scanner(System.in);
    int[] myList = new int [100];

    System.out.print(" Please enter a number betwen 1 and 100: ");
    int num = input.nextInt();
    if (num > 100)
    {
        System.out.println("No Match Found!");
    }   
        Random generator = new Random();
        int randomIndex = generator.nextInt(myList.length);


    if (num <= 100)
     {
         System.out.println(randomIndex);
         System.out.println("We found your number"+num+" at position YY in the array");
        }
    else;

3 个答案:

答案 0 :(得分:1)

您可以a)扫描整个阵列:

int index = 0;
boolean isNumberPresent = false;
while (index < array.length && !isNumberPresent) {
   if (array[index]==num) {
      isNumberPresent = true;
   }
   else {
     index++;
   }
}
// if isNumberPresent = true, then index now contains the number position, otherwise it will be = to array.length if the number is not there.

或者你可以b)使用诸如arraylist之类的集合而不是数组,并使用.indexOf方法。

答案 1 :(得分:1)

这是如何:

int index = 0;
boolean noMatch = true;
for(int i=0; i<sizeofarray; i++) {
    if(array[i] == thenumberyouwanttomatch) {
        System.out.println("Number found at Index: " + i);
        index = i; //You can use this variable 'index' to access it's corresponding value outside the loop by using the term array[index]
        noMatch = false;
        break; //To Break from the loop and used only if there are no repetitions allowed
    }
}
if(noMatch) {
    System.out.println("Number not found at any index. Search failed");
}

答案 2 :(得分:0)

为了让您更快地搜索,为什么不使用Hashing / Hashmap。其他选项是:由于您的随机数是有限的(1-100),您可能希望使用您的数字作为索引。

如果你只是想知道数字是否存在,那么它可以是布尔数组,或者知道数量是一个短/ int数组。