我的教授说我不能使用图书馆和东西。我有我的代码库:
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++)
{
}
}
答案 0 :(得分:0)
这比评论更容易放在这里,但它并不是真正的答案:)
你有一个很好的开始 - 而不是通过字母和找到匹配,每次遇到一个字母时,通过字符串并递增你的字母计数器(是的,这听起来也很奇怪)。
首先将字符串转换为小写或大写字母,您只需根据现有代码计算字母数,而不是它是低或高。
答案 1 :(得分:0)
如果您只需计算给定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]中,即数组中的第一个位置。
此外,此代码不会对任何非字母表的字符执行任何操作。