网址:
http://practiceit.cs.washington.edu/problem.jsp?category=Building+Java+Programs%2C+3rd+edition%2FBJP3+Chapter+7&problem=bjp3-7-e18-wordLengths
Write a method called wordLengths
that accepts aScanner
representing an input file as its argument. Your method should read from the given file, count the number of letters in each token in the file, and output a result diagram of how many words contain each number of letters.Use tabs before the asterisks so that they'll line up. If there are no words of a given length, omit that line from the output.
方法1:
public void wordLengths(Scanner scanner){
String str = null;
String string = "";
//scanner->String
while (scanner.hasNext()) {
String inStr= scanner.next();
if(!"".equals(inStr)){
if("".equals(string)){
string=inStr;
}else{
string=string+"#"+inStr;
}
}
}
String[] strArray=string.split("#");
//将所有长度放进一个数组a[]中,创建一个新的数组count[],下标长度应该为a[]的最大值。
//下标是a中的元素,元素是a[i]重复的.输出count元素不为0的元素的下标,元素值,输出***;
int[] a = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
a[i] = strArray[i].length();
}
int max = 0;
for (int i = 0; i < strArray.length; i++) {
if (max <= a[i]) {
max = a[i];
}
}
int[] count = new int[max+1];
for (int i = 0; i < strArray.length; i++) {
count[a[i]]++;
}
for (int i = 0; i < max+1; i++) {
if (count[i] != 0) {
System.out.println(i + ": " + count[i] + "\t" + print(count[i]));
}
}
}
public static String print(int a) {
String p = "";
for (int i = 1; i <= a; i++) {
p += "*";
}
return p;
}
方法2:
public void wordLengths(Scanner scanner){
String str = null;
String string="";
while (scanner.hasNext()) {
String inStr= scanner.next();
if(!"".equals(inStr)){
if("".equals(string)){
string=inStr;
}else{
string=string+"#"+inStr;
}
}
}
String[] strArray=string.split("#");
int[] countArray=new int[strArray.length];
for(int i=0;i<strArray.length;i++){
countArray[i]=strArray[i].length();
}
Arrays.sort(countArray);
int count=1;
for(int j=0;j<countArray.length-1;j++){
if(countArray[j]!=0){
if(countArray[j]==countArray[j+1]){
count++;
}else{ String temp="";
for(int n=0;n<count;n++){
temp=temp+"*";
}
System.out.println(countArray[j]+": "+count+"\t"+temp);
count=1;
}
}
}
if(countArray[countArray.length-1]==countArray[countArray.length-2]){
String temp="";
for(int n=0;n<count;n++){
temp=temp+"*";
}
System.out.println(countArray[countArray.length-1]+": "+count+"\t"+temp);
}
}