[英]Counting number of times a letter occurs in a string without using libraries
我的教授說我不能使用圖書館和東西。 我的庫中有代碼:
String phrase = keyboard.nextLine(); //Input.
int addr = phrase.length();
Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(addr, 26)); //there are 26 character in our alphabet. It makes a map and maps our the characters.
for (int i = 0; i < addr; ++i)//this area reads the string then, tells how many times each character appeared. Loops for each chracter.
{
char charAt = phrase.charAt(i);
if (!numChars.containsKey(charAt))
{
numChars.put(charAt, 1);
}
else if (numChars.containsKey(charAt))
{
numChars.put(charAt, 0);
}
else
{
numChars.put(charAt, numChars.get(charAt) + 1);
}
}
System.out.println(phrase);//outputs phrase written by user.
System.out.println(numChars);//outputs results of the code above
// this code reads which one appeared the most.
int FreqChar = 0;
char frequentCh = ' ';
for (int f = 0; f < phrase.length(); f++)
{
char poop = phrase.charAt(f);
int banana = 0;
for (int j = phrase.indexOf(poop); j != -1; j = phrase.indexOf(poop, j + 1))
{
frequentCh++;
}
if (banana > FreqChar)
{
FreqChar = banana;*/
這是我到目前為止沒有庫的程序。 我需要幫助將其轉換為數組。
import java.util.*;
public class LetCount
{
public static final int NUMCHARS = 26; //26 chars in alphabet.
// int addr(char ch) returns the equivalent integer address for the letter
// given in ch, 'A' returns 1, 'Z' returns 26 and all other letters return
// their corresponding position as well. felt this is important.
public static int addr(char ch)
{
return (int) ch - (int) 'A' + 1;
}
// Required method definitions for (1) analyzing each character in an input
// line to update the appropriate count; (2) determining most frequent letter;
// (3) determining least frequent letter; and (4) printing final results
// should be defined here.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in); // for reading input
int[] count = new int [NUMCHARS]; // count of characters
String phrase = keyboard.nextLine(); //Input.
int addr = phrase.length();
for(char ch = 'A'; ch <= 'Z'; ch++)
{
}
}
這比在評論中更容易放在這里,但這並不是真正的答案:)
您已經有了一個不錯的開始-不用遍歷字母並找到匹配項,而是每次遇到一個字母時都要遍歷字符串並增加字母計數器(是的,這聽起來也很奇怪)。
首先將字符串轉換為小寫或大寫字母,您只需要計算字母,而無需根據現有代碼將其大小寫。
如果您只需要計算給定String中的所有字母並將其存儲在數組中,請嘗試以下操作:
String str = phrase.toUpperCase();
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int charPositionInArray = c - 'A';
if(charPositionInArray < 26){
count[charPositionInArray] += 1;
}
}
另外,數組的索引從0開始,因此我假設您希望將'A'的計數存儲在count [0]中,即數組中的第一個位置。
此外,此代碼對非字母的任何字符均不執行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.