我已经生成了一个随机数组,我需要一种方法来返回用户输入值的索引。因此,如果它给出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;
}
}
答案 0 :(得分:0)
首先,请修正您的问题标题。
现在解决方案。你会如何在现实生活中做到这一点?如果匹配搜索到的值,您将遍历数组并检查每个条目。 这就是你如何用Java做到这一点。
public static int findValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) { // iterate over the content of the given array
if (array[i] == value) { // check if the current entry matches the searched value
return i; // if it does return the index of the entry
}
}
return -1; // value not found, return -1
}
以下是调用此方法的示例:
public static void main(String[] args) {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
System.out.println(findValue(array, 6));
}
这将打印5
,因为数字6位于给定数组中的第5个位置。请注意,索引以0
开头。