gpt4 book ai didi

java - 第二个循环背后的逻辑

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:39 25 4
gpt4 key购买 nike

最近,我被要求完成一项作业,即编写一个简单的 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]);
}


}

}

两种方式的结果都是相同的,但想知道它是否更有效?

最佳答案

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

关于java - 第二个循环背后的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com