2014-09-05 58 views
-3

我有一個隨機數組生成,我需要一種方法來返回用戶輸入值的索引。因此,如果它給出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; 

} 


} 
+1

如何在紙張上的未排序名稱列表中找到名稱?這是完全一樣的問題,任何人都可以自然解決。 – Dici 2014-09-05 22:40:24

+1

你的標題和描述看起來不匹配。 – 2014-09-05 22:41:13

回答

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是在給定陣列中的第五位置。請記住,索引始於0

+0

非常感謝。我只在這個課上學了兩個星期,剛開始做java編程,所以我試圖掌握很多這些東西。 – 2014-09-05 23:03:52