Недавно меня попросили работать над назначением, которое должно написать простое приложение Java, которое считывает телефонный номер в виде строки и печатает частоту каждой цифры в телефонном номере. Однако, после того, как смотреть на это тщательно с моим партнером, я попал под некоторое замешательство относительно того, почему мне нужно второй линии контура, коды являются следующиеLogic Behind 2nd Loop
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]);
}
}
}
В результате одно и то же в любом случае, но если возможно, было интересно, если он более эффективен?