Как посчитать все буквенные символы в массиве?

1

Поэтому в основном моя цель - сделать программу, которая вводит пользователя и изменяет его и печатает обратный символ обратно пользователю в виде закодированного сообщения. Прямо сейчас мне нужно распечатать статистику введенной пользователем строки. Как подсчитать количество вхождений разных букв из пользовательской строки. У меня это до сих пор.

   import java.util.*;

  public class SecretCodeMachine
 {
  public static void main(String[]args)
 {
    //object accessing the non static methods
    SecretCodeMachine a = new SecretCodeMachine();

    //input stream
    Scanner in = new Scanner (System.in);
    Scanner i = new Scanner (System.in);

    //prompt the user
    System.out.println("Please input your secret message.");
    String input = in.nextLine();

    //calls the encodedMessage() method; equals the return value to varaible
    String encodedMessage = a.encodeMessage(input);

    //message and prompt
    System.out.println("Encoded message: " + encodedMessage);
    System.out.println("Enter the code in here to get the original message back.");
    String input2 = i.nextLine();

    //if statements saying that if the input equals the encoed message...
    if (input2.equals(encodedMessage))
    {
        //print this
        System.out.println("Original Message: " + input);
    }
    else
    {
        //prints when doesnt equal
        System.out.println("Message not found.");
    }

    //closes the input stream
    i.close();
    in.close();

}
//method for encoding the string from array
public String encodeMessage(String pass)
{
    //passes the parameter string and puts it in an array ()
    char[] toArray = pass.toCharArray();

    for (int i = 0; i < toArray.length; i++) 
    {
        //does the lower case characters
        if (toArray[i] >= 'a' && toArray[i] <= 'z') 
        {
            if (toArray[i] - 'a' <= 13) toArray[i] = (char) ('z' - (toArray[i] - 'a'));
            else toArray[i] = (char) ('a' + ('z' - toArray[i]));
        }

        //does the upper case characters
        else if(toArray[i] >= 'A' && toArray[i] <= 'Z')
        {
            if (toArray[i] - 'A' <= 13) toArray[i] = (char) ('Z' - (toArray[i] - 'A'));
            else toArray[i] = (char) ('A' + ('Z' - toArray[i]));
        }
        //if the characters are non alphatbetic 
        else 
        {
            toArray[i] = toArray[i];
        }
    }

    //converts the toArray back to new string 
    String encodedMessage = new String(toArray);

    //returns the encodedMessage string
    return encodedMessage;
}

}

Итак, как бы я отследил все буквы, введенные пользователем?

  • 0
    Вот стратегия: 1) Положите все символы, которые пользователь ввел в Set . 2) Сохраняйте Map каждого из символов в Set и его частоту (которую вы собираетесь выяснить), инициализированную нулем. 3) Перебирайте каждый символ в строке ввода пользователя и увеличивайте частоту символа на Map если он найден в Set .
  • 0
    Вы можете использовать хеш-карту <ключ, значение>, пример <a, 2> <b, 4>
Теги:
nested-loops
counter

2 ответа

0
Лучший ответ
 public class SecretCodeMachine
 {
     HashMap<Character, Integer> charCounts = new HashMap<Character, Integer>();//add hashmap here

Код для обновления счетчика для каждого символа:

for (int i = 0; i < toArray.length; i++) 
    {
        //does the lower case characters

        //update count for character
        if(charCounts.get(toArray[i]) != null)
        {
            charCounts.put(toArray[i], (charCounts.get(toArray[i]) + 1));
        }
        else
        {
            charCounts.put(toArray[i], 1);
        }

        if (toArray[i] >= 'a' && toArray[i] <= 'z') 
        {
            if (toArray[i] - 'a' <= 13) toArray[i] = (char) ('z' - (toArray[i] - 'a'));
            else toArray[i] = (char) ('a' + ('z' - toArray[i]));
        }

        //does the upper case characters
        else if(toArray[i] >= 'A' && toArray[i] <= 'Z')
        {
            if (toArray[i] - 'A' <= 13) toArray[i] = (char) ('Z' - (toArray[i] - 'A'));
            else toArray[i] = (char) ('A' + ('Z' - toArray[i]));
        }
        //if the characters are non alphatbetic 
        else 
        {
            toArray[i] = toArray[i];
        }
    }

Вы можете использовать hashmap для хранения символов и целых чисел. Пара ключей/значений содержит только одну запись для каждого ключа на карту. пример

0

Ведите карту с ключом как символ и считайте целой. Ниже приведен метод, который может помочь вам:

public Map<Character, Integer> getCharCount(String input) {
  Map<Character, Integer> charCountMap = new HashMap<Character, Integer>();
  Integer count;
  for (int i =0; i<input.length();i++) {
    count = charCountMap.get(input.charAt(i));
    if (count == null) {
      charCountMap.put(input.charAt(i), 1);
    } else {
      charCountMap.put(input.charAt(i), count + 1);
    } 
  }
  return charCountMap;
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню