我有一個隨機數組生成,我需要一種方法來返回用戶輸入值的索引。因此,如果它給出8個隨機數,它會要求用戶在數組中找到一個值。一旦輸入該值,它需要返回該值的第一個索引。我們在課堂上沒有經過這麼多,我不知道最好的方式來回報。這是我到目前爲止:返回數組中的值數不能被2整除
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;
}
}
如何在紙張上的未排序名稱列表中找到名稱?這是完全一樣的問題,任何人都可以自然解決。 – Dici 2014-09-05 22:40:24
你的標題和描述看起來不匹配。 – 2014-09-05 22:41:13