无法分配变量以显示数组的索引

时间:2017-06-09 23:28:29

标签: java arrays

我正在编写一个程序,我生成100个随机数,我提示用户输入一个数字,程序说这个数字是在索引XX找到的。或者说没有找到该号码。这就是我所拥有的:

import java.util.*;
import java.util.Random;
public class lab1
{
public static void main (String[]args)
{
    //Let's create an array with 100 random numbers
    int [] randomArray = new int [100];
    Random randomGenerator = new Random();


    for(int i = 0; i < randomArray.length; i++)
    {
        randomArray[i] = randomGenerator.nextInt(100) + 1;
    }
//ask user to enter a number between 1 and 100
    Scanner input = new Scanner(System.in);
    int searchNumber;

    System.out.println("Please enter a number between 1 and 100 to search 
for: ");
    searchNumber = input.nextInt();

    boolean found = false;


    for(int i = 0; i < randomArray.length; i++)
    {
        if(searchNumber == randomArray[i])
        {
            found = true;
            break;//Exits the loop
        }
    }
    if(found)
    {
        System.out.println("We have found your number, " + searchNumber + " 
at index " + index);
    }
    else
    {
        System.out.println("We did not find your number");
    }
}
}

当我的程序找到一个数字时,我无法显示索引,我知道这是因为变量“i”仅在for循环中定义。我不确定如何在for循环之外创建一个新变量,并将i赋值给for循环中的变量。

2 个答案:

答案 0 :(得分:0)

在循环之外声明i,即

int i;
for(i = 0; i < randomArray.length; i++)
{
    ...
    ...
    ...
}

然后您可以使用i中的索引println

if(found)
{
     System.out.println("We have found your number, " + searchNumber + "at index " + i);
}
else
{
     System.out.println("We did not find your number");
}

答案 1 :(得分:0)

你一直有正确的想法,甚至完美地表达了它:&#34; ...在for循环之外创建一个新变量,并将i分配给for循环内的变量&#34; :

    int foundAt = -1;
    for(int i = 0; i < randomArray.length; i++)
    {
        if(searchNumber == randomArray[i])
        {
            foundAt = i;
            break;//Exits the loop
        }
    }
    if(foundAt != -1)
    {
        System.out.println("We have found your number, " + searchNumber + " 
at index " + foundAt);
    }
    else
    {
        System.out.println("We did not find your number");
    }
}