Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 单词词典:需要扫描每个元素的单词长度并使其可搜索_Java - Fatal编程技术网

Java 单词词典:需要扫描每个元素的单词长度并使其可搜索

Java 单词词典:需要扫描每个元素的单词长度并使其可搜索,java,Java,我已将一个单词文件转换为字符串数组。我需要以某种方式将数组转换为字长列表,并使其可搜索。换句话说,我需要能够输入字长(比如说,5),并且只显示字长为5的单词。帮忙 public static void main(String[] args) throws IOException { String token1 = ""; Scanner scan = new Scanner(new File("No.txt")); List<String> temps = ne

我已将一个单词文件转换为字符串数组。我需要以某种方式将数组转换为字长列表,并使其可搜索。换句话说,我需要能够输入字长(比如说,5),并且只显示字长为5的单词。帮忙

public static void main(String[] args) throws IOException {    
  String token1 = ""; 
  Scanner scan = new Scanner(new File("No.txt"));
  List<String> temps = new ArrayList<String>();
    while (scan.hasNext()){ 
           token1 = scan.next(); 
           temps.add(token1);
     }
  scan.close();
  String[] tempsArray = temps.toArray(new String[0]);
  for (String s : tempsArray) {
publicstaticvoidmain(字符串[]args)抛出IOException{
字符串标记1=“”;
扫描仪扫描=新扫描仪(新文件(“No.txt”);
List temps=new ArrayList();
而(scan.hasNext()){
token1=scan.next();
临时添加(标记1);
}
scan.close();
字符串[]tempsArray=temps.toArray(新字符串[0]);
用于(字符串s:tempsArray){

您不需要使用数组。更准确地说,您需要的是集合:和;因为您想使用
映射

含义:一个使用“单词长度”作为键的映射;映射的条目是一个包含所有具有该长度的单词的列表。下面是一些代码:

Map<Integer, List<String>> wordsByLength = new HashMap<>();
// now you have to fill that map; lets assume tempsArray contains all your words
for (String s : tempsArray) {
  List<String> listForCurrentLength = wordsByLength.get(s.length());
  if (listForCurrentLength == null) {
    listForCurrentLength = new ArrayList<>();
  }
  listForCurrentLength.add(s);
  wordsByLength.put(s.length(), listForCurrentLength);
Map wordsByLength=newhashmap();
//现在您必须填写该地图;假设tempsArray包含您的所有单词
用于(字符串s:tempsArray){
List listForCurrentLength=wordsByLength.get(s.length());
如果(listForCurrentLength==null){
listForCurrentLength=新的ArrayList();
}
listForCurrentLength.add(s);
wordsByLength.put(s.length(),listForCurrentLength);
其基本思想是迭代已经得到的数组;对于其中的每个字符串……根据其长度将其放入该映射中


(上面的内容只是写下来的;既没有编译也没有测试;正如所说的,它的意思是作为“伪代码”让您继续)

在数组中循环,比较长度?看一看,例如,您可以使用
Multimap
按长度收集单词。对我的答案有任何评论/反馈吗?是否有帮助;我可以添加一些内容以使您可以接受?