我需要获取此代码以获取用户输入并告诉我有多少个单字母单词,双字母单词,三个字母单词等等。此代码编译,但它只给出了使用最多字母的单词的次数。例如,如果用户输入是"我想知道为什么这不起作用"输出将是一个七个字母的单词。它并没有告诉我所有其他字母单词的使用次数。
import java.util.*;
import java.io.*;
public class Analysis B { //open class
public static String input;
public static String stringB;
public static void main (String args []) { //open main
System.out.println("Please enter a line of text for analysis:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
input = input.toLowerCase();
System.out.println("Analysis B:");//Analysis B
System.out.println("Word length: " + " Frequency: ");
System.out.println(AnalysisB(stringB));
} // close main
public static String AnalysisB (String stringB) { // open analysis B
String [] words = input.split(" ");
int largest = 0;
for (int i = 0; i < words.length; i++) { //open for
largest = Math.max( words[i].length(), largest); // get the largest value
} //close for
int [] frequencies = new int[ largest + 1 ];
for (int i = 0; i < words.length; i++) { //open for
frequencies[words[i].length()]++;
} //close for
for (int i = 0; i < frequencies.length; i++) { //open for
if (frequencies[i] > 0 ) { //open if
stringB =(i + "-letter words" + " " + frequencies[i]);
} //close if
} //close for
return stringB;
} // close analysis B
} //close class
答案 0 :(得分:0)
这是你的问题:
stringB =(i + "-letter words" + " " + frequencies[i]);
每次运行此代码行时,它会为stringB
分配一个新值,覆盖以前的值。相反,你希望它看起来像这样:
stringB += (i + "-letter words" + " " + frequencies[i] + "\n");
+=
运算符将添加到stringB
而不是替换它("\n"
将确保每次都添加到新行。
顺便说一下,没有必要导入java.io.*
,因为它没有在您的程序中使用。 java.io
处理文件操作。
答案 1 :(得分:0)
以下是使用已排序的HashMap(TreeMap)执行此操作的方法:
public static void AnalysisB (String input)
{
String [] words = input.split(" ");
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (String w : words)
{
int len = w.length();
Integer freq = map.get(len);
if (freq == null)
{
map.put(len, 1);
}
else
{
map.put(len, freq + 1);
}
}
for (Iterator<Integer> iter = map.keySet().iterator(); iter.hasNext(); )
{
int len = iter.next();
System.out.println(len + "-letter words" + " " + map.get(len));
}
}
注意:由于您只是在方法中打印出频率,因此我将方法设为无效。
答案 2 :(得分:0)
试试这个。
items
和
log
结果:
static func p(level: LogLevel, items: Any..., file: String = #file, line: Int = #line) {
log(level: level, file: file, line: line, items: items)
}
static func d(items: Any..., file: String = #file, line: Int = #line) {
log(level: .Debug, file: file, line: line, items: items)
}
static func i(items: Any..., file: String = #file, line: Int = #line) {
log(level: .Info, file: file, line: line, items: items)
}
// other level-specific functions here...
}