【问题标题】:Logic Behind 2nd Loop第二循环背后的逻辑
【发布时间】:2015-11-12 03:06:05
【问题描述】:

最近我被要求完成一项任务,即编写一个简单的 Java 应用程序,该应用程序将电话号码作为字符串读取并打印出电话号码中每个数字的频率。然而,在和我的伙伴仔细研究之后,我对为什么需要第二个循环行感到有些困惑,代码如下

public class CharacterFrequency {

public static Scanner kbd = new Scanner(System.in);

public static int MAXSIZE=10; //Constant for array size and easy change

public static void main(String[] args) {

    int telephoneNumArrayIndex = 0; //index where array will start checking
    char [] telephoneNumArray = new char[MAXSIZE]; //array holding tel Number digits.

    String telephoneNumber;//string that will that will read input from user.

    System.out.print("Please Enter a 10-digit Telephone Number: ");
    telephoneNumber = kbd.next();

    System.out.println("\nThe Following is the Number of Times Each Digit Appears:\n");

    //loop that will check and test  array for digits and ignore "white space" 
    //characters (-,*,., ,etc)
    for (int i = 0; i < telephoneNumber.length(); i++) {
        if (telephoneNumber.charAt(i) >= (char) 48
                && telephoneNumber.charAt(i) <= (char) 57) {
            telephoneNumArray[telephoneNumArrayIndex++] = telephoneNumber.charAt(i);
        }
    }

    //reasoning behind the loop. ??????
    int[] counter = new int[MAXSIZE];
    //loop to fill 
    for (int i = 0; i < counter.length; i++) {
        counter[i] = 0;
        System.out.println(counter[i]);
    }

    //loop that stores the frequency of each digit 0-9 to its corresponding array 
    //index. the char is then parsed to convert to int datatype in order to use the counter
    //in the array.
    for (int i = 0; i < telephoneNumArray.length; i++) {
        for (int j = 0; j < 10; j++) {
            if (telephoneNumArray[i] == (char) (j + 48)) {
                counter[j]++;
            }
        }
    }

    //loop that will display the frequency (counter[i]) of each digit (i),
    //used in a typical U.S. phone number by looping through each index of the array
    //and printing the number corresponding to that count from 0-9 

    for (int i = 0; i < telephoneNumArray.length; i++) {
        System.out.println(i + " - " + counter[i]);
    }


}

}

结果都是一样的,但想知道是否更有效?

【问题讨论】:

    标签: java loops logic


    【解决方案1】:

    第二个循环的目的是将计数器数组中的所有值初始化为 0。 然而在 Java 中,一个基元数组将每个元素初始化为其默认值。 int 的默认值为 0,因此计数器数组已将所有内容设置为 0。因此该循环毫无意义,可以删除。

    【讨论】:

      【解决方案2】:

      有问题的循环用于初始化计数数组中的值。许多语言中未初始化的变量是null,如果您尝试计算递增它(即操作null +1),您将收到异常,因为这不是受支持的操作。

      这是一个有效的问题,也是在许多语言中具有这样的循环(或其他初始化过程)的原因。但是在 Java 中它不是必需的。在 Java 中,简单类型不能为空。这意味着如果您不初始化它们,它们将变为默认值(整数和短裤为 0)。

      请参阅this 问题以更深入地分析该问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多