【发布时间】:2019-05-19 07:39:09
【问题描述】:
我正在编写一个 java 程序逻辑,用于打印带有出现次数和行号的 wrod。下面是代码
package test;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class Countcharacters {
/**
* @param args
*/
static HashMap<String, Integer> countcharact=new HashMap<>();
static HashMap<String, String> linenumbertrack=new HashMap<>();
static int count=1;
static void countwords(String line){
//System.out.println(line);
String[] input=line.split("\\s");
int j=0;
String linenumber="";
for(int i=0;i<input.length;i++){
//System.out.println(input[i]);
if(countcharact.containsKey(input[i])==true){
j=countcharact.get(input[i]);
linenumber=linenumbertrack.get(input[i]);
countcharact.put(input[i],j+1);
linenumbertrack.put(input[i],linenumber+", "+count);
}
else{
countcharact.put(input[i], 1);
linenumbertrack.put(input[i],count+"" );
}
}
count++;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String inp="the quick brown fox jumped over the lazy dog's bowl.\nthe dog was angry with the fox for considering him lazy.";
String[] line=inp.split("\n");
for(int i=0;i<line.length;i++){
Countcharacters.countwords(line[i]);
}
Set<String> s=countcharact.keySet();
for(String c:s){
System.out.println(c+" "+countcharact.get(c)+" "+"["+linenumbertrack.get(c)+"]");
}
}
}
我得到的输出是
over 1 [1]
quick 1 [1]
lazy. 1 [2]
lazy 1 [1]
considering 1 [2]
jumped 1 [1]
was 1 [2]
for 1 [2]
angry 1 [2]
brown 1 [1]
him 1 [2]
fox 2 [1, 2]
the 4 [1, 1, 2, 2]
with 1 [2]
bowl. 1 [1]
dog's 1 [1]
dog 1 [2]
但我有两个问题。
第一个:如果您看到“the”的出现次数为 4,但行数为 [1,1,2,2] 而应仅为 [1,2]。
2nd:我想对它们进行排序。它应该首先按基数降序排列,然后按字母顺序排列。
像这样:
the 4 [1,2]
fox 2 [1,2]
lazy 2 [1,2]
angry 1 [1]
bowl 1 [1]
.
.
【问题讨论】:
-
您遇到问题的代码是什么?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同?请提供minimal reproducible example。
-
嗨,我扩展了我的问题
标签: java algorithm design-patterns collections java-8