【发布时间】:2017-04-11 01:39:14
【问题描述】:
我需要获取多行文本并计算每行中每个字母的出现次数。最后一行必须以句点结尾。我被要求创建一个长度为 26 的 int 数组,其中 arrayName[0] = number of a's、arrayName[1] = number of b's 等,并且需要忽略字母大小写。我无法检查每个字母的出现并使用正确的出现次数定义索引变量。到目前为止我的代码:
import java.util.Scanner;
public class LetterCounter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[] textBlock = new String[10];
System.out.println("Enter text.");
int index;
//Allows me to type in something for all "lines" of text until I end one with a period.
for(index = 0; index < textBlock.length; index++)
{
textBlock[index] = input.nextLine();
if(textBlock[index].contains("."))
{
System.out.println("Period found");
break;
}
}
//Outputs what the user printed except for the lines not typed in (they return null).
System.out.println("Text input by user:");
for(index = 0; index < textBlock.length; index++)
{
if(textBlock[index] != null)
{
System.out.println(textBlock[index]);
}
}
//int array
int[] occurrences = new int[26];
//used to turn letter into number
char letter = 'a' - 49;
char letter2 = 'b' - 49;
char letter3 = 'c' - 49;
//checks that numbers are correct (return "0" for a, "1" for b, and "2" for c)
System.out.println("Number value of a: " + letter);
System.out.println("Number value of b: " + letter2);
System.out.println("Number value of c: " + letter3);
}// End of main
}//End of program
【问题讨论】:
-
对于初学者,我认为您想在循环之外声明数组。您可能想强制您阅读的每个字母小写。然后在检查“a”到“z”中的字母后,++读取字母索引处的数组-“a”。
标签: java arrays string letters find-occurrences