【发布时间】:2014-09-05 22:37:02
【问题描述】:
我生成了一个随机数组,我需要一种方法来返回用户输入值的索引。因此,如果它给出 8 个随机数,它会要求用户在数组中查找一个值。一旦输入该值,它需要返回该值的第一个索引。我们在课堂上还没有讲过这么多,我不知道最好的方法来回报这个。到目前为止,这是我所拥有的:
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
/*
** 3. write findValue **
*/
int index = findValue(array, target);
if (index == -1)
{
// target was not found
System.out.println("value " + target + " not found");
}
else
{
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
/*
allocate a random int[] array with size elements, fill with
random values between 0 and 100
*/
public static int[] generateRandomArray(int size)
{
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i=0; i<rval.length; i++)
{
rval[i] = rand.nextInt(100);
}
return rval;
}
/*
print out the contents of array on one line, separated by delim
*/
public static void printArray(int[] array, String delim)
{
// your code goes here
System.out.println (Arrays.toString(array));
}
/*
return the count of values in array that are not divisible evenly by 2
*/
public static int countOdds(int[] array)
{
int count=0;
// your code goes here
for (int i=0; i<array.length; i++){
if (array[i] %2 !=0) {
count++;
}
}
return count;
}
/*
return the first index of value in array. Return -1 if value is not present.
*/
public static int findValue(int[] array, int value)
{
// your code goes here
return -1;
}
}
【问题讨论】:
-
如何在纸上未排序的名字列表中找到一个名字?完全一样的问题,自然谁都能解决。
-
您的标题和描述似乎不匹配。