我正在尝试编写一个程序,在生成随机数后,返回数组中包含等于槽索引的值的槽数,然后将数组的每个元素打印在单独的与星号对齐。 (假设看起来像这样:)
Enter the array size: 4
a[0] = 2
a[1] = 1 *
a[2] = 0
a[3] = 2
There are 1 slots where the index is the same as the value.
但我失败得很惨,任何朝着正确方向的插入将不胜感激。这是我到目前为止所拥有的:
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i;
System.out.println("Enter the array size: ");
i = in.nextInt();
}
/**
* Fills an array with random integers in the range from zero to one less
* than the array size.
*
* @param array
* the array to fill with random integers
*/
public static void fillArrayWithRandomInts(int array[]) {
java.util.Random random = new java.util.Random(13);
for (int i = 0; i < array.length; ++i)
array[i] = (int) (random.nextDouble() * array.length);
}
public static int countSlotsWithIndexEqualToValue(int array[]) {
int[] value = new int[13];
for (int i = 0; i < array.length; i++) {
if (value[13] == array[13])
;
}
return value[13];
}
public static void printArray(int array[]) {
}
}
最佳答案
您需要以相同的方法将支票和打印结合起来。如果您需要统计有多少个这样的组合,则需要添加一个计数器。
public static void countSlotsAndPrint(int[] a) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
System.out.print("a[" + i + "] = " + a[i]); // print the array as per required
if (i == array[i]){
System.out.println(" *"); // if index is equal to the value, then print the *
counter++;
} else {
System.out.println(); // blank line to go to the next line
}
}
System.out.println("There are " + counter + " slots where the index is the same as the value.");
}
关于java - 返回数组中包含等于槽索引的值的槽数量的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19853659/