java - 返回数组中包含等于槽索引的值的槽数量的计数

标签 java arrays if-statement for-loop

我正在尝试编写一个程序,在生成随机数后,返回数组中包含等于槽索引的值的槽数,然后将数组的每个元素打印在单独的与星号对齐。 (假设看起来像这样:)

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/

相关文章:

java - 如何将表的JSON格式的数据行字符串转换为android中的java数组

java - Camel,使用字段条件分割带有 header 的大型 XML 文件

java - 从数组到ArrayList

JavaScript 单行 'if' 语句 - 最佳语法,这个替代方案?

swift - 如何比较两个字符串以查看其中一个是否大于另一个

java - 为什么不允许外部接口(interface)为 HashMap 提供 hashCode/equals?

Java序列化和重复对象

java - 将许多不同的 Swing 对象添加到面板/框架的有效方法。 ( java )

javascript - 如何从包含子字符串的对象数组中提取元素 - Javascript 和 Angular 5

javascript - 如何验证字段是否具有必需属性或不为空?