【问题标题】:Return count of values in array not divisible evenly by 2返回数组中值的计数不能被 2 整除
【发布时间】: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;

}


}

【问题讨论】:

  • 如何在纸上未排序的名字列表中找到一个名字?完全一样的问题,自然谁都能解决。
  • 您的标题和描述似乎不匹配。

标签: java arrays return


【解决方案1】:

首先,请修正你的问题标题。

现在是解决方案。在现实生活中你会如何做到这一点?您将遍历数组并检查每个条目是否与搜索的值匹配。 这正是你在 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 开头。

【讨论】:

  • 非常感谢。我才上这门课 2 周,刚开始做 java 编程,所以我试图掌握很多这些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
相关资源
最近更新 更多