使用说明:
编写了一个程序,它将读取一行以句点结尾的文本,作为一个哨位值。显示文本中出现的所有字母,每行一个字母,按字母顺序排列,以及每个字母在文本中出现的次数。使用长度为26的基类型int数组,以便索引0处的元素包含
as数,索引1包含bs数等。
package alphabetize;
import java.util.*;
public class Alphabetize
{
private static void number(String s)
{
int[] array = new int[26];
s = s.toUpperCase();
System.out.println(s);
for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println("|" + (char) ('A' + i) + "|" + array[i] + "|");
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String aString = ".";
while (true)
{
System.out.println("Please enter sentence with a period to end");
aString = keyboard.nextLine();
if (".".equals(aString))
{
System.exit(0);
}
number(aString);
}
}
}还有时间问题..。它似乎不像我那样工作。
发布于 2011-11-14 04:35:49
考虑到这是一个家庭作业,并且说明是非常具体的,您应该逐字阅读文本,而不是使用内置函数。
如果您的文本文件类似于
abcabca.输出应该是a出现三次,b出现两次等。
所以你的阿尔法应该是
H 110输出arr0 0.25中更新计数器.25行<代码>H 211G 212
发布于 2011-11-14 04:41:29
,
现在,您将字符串字符放在一个循环中,并必须检查该字符是什么样的:
if its a 'a' : increase the value at index 0 by 1.
if its a 'd' : increase the value at index 3 by 1. 就像聪明一样。
稍后,您将使用a,z以及0到25之间的索引显示整个数组。
建议:如果不需要使用数组,并且可以使用任何其他数据结构,则可以非常容易地在HashMap中实现相同的数据结构。通过保持'a','z‘作为键,计数作为相应的值。然后检索和显示这些值也会更容易。
发布于 2011-11-14 04:45:58
在读取输入行后,需要一个int数组(例如,int[] counts = new int[26];),在循环中逐字符检查它。如果字符不是句点,则增加计数数组的适当元素。(如果字符为a,则增量counts[0];如果是b、增量counts[1];等等:您可以从字符中减去a以获得适当的索引。)找到句点时,退出循环并打印结果(可能使用第二个循环)。
https://stackoverflow.com/questions/8117352
复制相似问题