Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.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,我有一个类,它接收一个txt文件,其中包含艺术家及其流派的格式: 阿巴岩 贝多芬古典音乐 我正在尝试编写一个方法“public int count(String-genre)”,它计算单词/类型出现的次数。例如,对于rock,它需要计算摇滚艺术家的数量并满足我的测试用例: public class ArtistTest { public static void main(String[] args) { Artists artists = new Artists(

我有一个类,它接收一个txt文件,其中包含艺术家及其流派的格式:
阿巴岩
贝多芬古典音乐

我正在尝试编写一个方法“public int count(String-genre)”,它计算单词/类型出现的次数。例如,对于rock,它需要计算摇滚艺术家的数量并满足我的测试用例:

public class ArtistTest
{
   public static void main(String[] args)
   {    
      Artists artists = new Artists();
      System.out.println(artists.count() + " artists in the list");
      System.out.println(artists.count("Rock") + " rock artists in the list\n");
我的初始计数方法成功地计算了艺术家的数量(我想有更好的方法)

到目前为止,我的代码是:

import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;

public class Artists {

    public static ArrayList<String> artists = new ArrayList<String>();

    public static void main(String[] args) {
        System.out.println(readArtists("artists30.txt"));
        System.out.println(artists + "\n");
    }

    public Artists() {
    }

    public static boolean readArtists(String fileName) {
        Scanner sc = null;
        try {
            File file = new File(fileName);
            if (file.createNewFile()) {
                System.out.println("err " + fileName);
                return false;
            }
            sc = new Scanner(file);
            while (sc.hasNextLine()) {
                artists.add(sc.nextLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sc != null) {
            sc.close();
        }
        return true;
    }

    public int count() {
        int count = artists.size();
        return count;
    }

    public int count(String genre) {
    }
}

只要你的映射是“艺术家”+“空间”+“流派”,你就可以尝试下面的代码。这将创建一个以所有类型为键的映射,该值是该类型的相应计数

class Grouper {

public static void main(String[] args) {
    var grouper = new Grouper();
    grouper.groupByGenre();
}

void groupByGenre() {
    List<String> musicCollection = List.of("Kid Rock", "Hello Rock", "Beethoven Classical");
    var collection = musicCollection.stream()
            .map(entry -> entry.split(" "))
            .filter(strings -> strings.length == 2)
            .map(strings -> new MusicCollection(strings[0], strings[1]))
            .collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
    System.out.println(collection);
}
}

class MusicCollection {
private final String artist;
private final String genre;

public MusicCollection(String artist, String genre) {
    this.artist = artist;
    this.genre = genre;
}

public String getArtist() {
    return artist;
}

public String getGenre() {
    return genre;
}

我是老派。所有这些新的东西让我头晕目眩。我喜欢把事情简单化。我的方法是做两件简单的事情:

  • 定义将表示每个艺术家信息的艺术家对象。该对象知道如何从数据文件中的一行构造自身

  • 在阅读《艺术家》时,创建第二个“按流派”索引,该索引将为您提供每种流派的艺术家列表

  • 我做的另一件事是使事物非静态,所以你实际上实例化了一个艺术家对象,以防你想要有多个艺术家列表

    这是我的表演:

    import java.util.*;
    import java.io.File;
    import java.util.Scanner;
    
    public class Artists {
    
        public class Artist {
    
            public String name;
            public String genre;
    
            public Artist(String line) {
                String[] parts = line.trim().split("\\s+");
                name = parts[0];
                genre = parts[1];
            }
        }
    
        private List<Artist> artists = new ArrayList<>();
        private Map<String, List<Artist>> genres = new HashMap<>();
    
        public boolean readArtists(String fileName) {
    
            Scanner sc = null;
            try {
                File file = new File(fileName);
                if (file.createNewFile()) {
                    System.out.println("err " + fileName);
                    return false;
                }
                sc = new Scanner(file);
                while (sc.hasNextLine()) {
                    // Turn the line into an Artist object
                    Artist artist = new Artist(sc.nextLine());
                    // Add it to the main list of artists
                    artists.add(artist);
                    // Add it to the per-genre index
                    if (!genres.containsKey(artist.genre))
                        genres.put(artist.genre, new ArrayList<>());
                    genres.get(artist.genre).add(artist);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (sc != null) {
                sc.close();
            }
            return true;
        }
    
        public int count() {
            return artists.size();
        }
    
        public int count(String genre) {
            if (genres.containsKey(genre))
                return genres.get(genre).size();
            return 0;
        }
    
        public static void main(String[] args) {
            Artists artists = new Artists();
            String filepath = "/tmp/artists30.txt";
            if (artists.readArtists(filepath)) {
                System.out.printf("Artist Count: %d\n", artists.count());
                System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
            }
            else {
                System.out.printf("Failed to read artists file '%s'\n", filepath);
            }
        }
    }
    
    结果:

    Artist Count: 7
    Rock Artist Count: 4
    

    好吧,如果你用一个字符串来同时保留艺术家和流派,我想很多方法会在你一到“儿童摇滚”的时候被打破。我会将艺术家和流派分为两个类域,并列出
    artist
    s,而不是
    String
    s。然后,您可以更轻松地计算某个流派的出现次数。请展示
    艺术家
    类。您需要了解从
    Java8
    引入的
    流API
    ,才能理解上述代码。@chocolateGooseBoosey签出编辑,并确实尝试投入一些时间学习流API,因为它非常强大。添加“导入java.util.Objects;“在topI,我喜欢这种更简单的方法。但是,有没有办法在boolean readArtists方法中扫描文本文件?我不知道你在问什么。我们现在不是还在这样做吗?
    readArtists
    只是一个实例方法,而不是静态(类)方法,但仍然读取文件并返回一个
    boolean
    。是否要在不首先创建
    Artists
    对象的情况下调用
    readArtists
    对象?我想过这样做,但我无法同时返回
    Artists
    对象和
    boolean
    结果。具体来说,这就是我的程序所做的ng赋值要求:“boolean readArtists(字符串文件名):将存储在作为参数传递的文件中的所有艺术家添加到列表中。如果成功打开文件,readArtists方法应返回true。否则,该方法应处理异常,显示包含丢失文件名称的适当错误消息,并返回false。“我编辑了帖子以包含测试该异常的测试类,我没有尝试更改该测试类。它正在抛出空指针异常空指针异常指向”返回genres.get(genre.size();"
    import java.util.*;
    import java.io.File;
    import java.util.Scanner;
    
    public class Artists {
    
        public class Artist {
    
            public String name;
            public String genre;
    
            public Artist(String line) {
                String[] parts = line.trim().split("\\s+");
                name = parts[0];
                genre = parts[1];
            }
        }
    
        private List<Artist> artists = new ArrayList<>();
        private Map<String, List<Artist>> genres = new HashMap<>();
    
        public boolean readArtists(String fileName) {
    
            Scanner sc = null;
            try {
                File file = new File(fileName);
                if (file.createNewFile()) {
                    System.out.println("err " + fileName);
                    return false;
                }
                sc = new Scanner(file);
                while (sc.hasNextLine()) {
                    // Turn the line into an Artist object
                    Artist artist = new Artist(sc.nextLine());
                    // Add it to the main list of artists
                    artists.add(artist);
                    // Add it to the per-genre index
                    if (!genres.containsKey(artist.genre))
                        genres.put(artist.genre, new ArrayList<>());
                    genres.get(artist.genre).add(artist);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (sc != null) {
                sc.close();
            }
            return true;
        }
    
        public int count() {
            return artists.size();
        }
    
        public int count(String genre) {
            if (genres.containsKey(genre))
                return genres.get(genre).size();
            return 0;
        }
    
        public static void main(String[] args) {
            Artists artists = new Artists();
            String filepath = "/tmp/artists30.txt";
            if (artists.readArtists(filepath)) {
                System.out.printf("Artist Count: %d\n", artists.count());
                System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
            }
            else {
                System.out.printf("Failed to read artists file '%s'\n", filepath);
            }
        }
    }
    
    Abba Pop
    Beethoven Classical
    Rush Rock
    Aerosmith Rock
    Mozart Classical
    AC/DC Rock
    Yes Rock
    
    Artist Count: 7
    Rock Artist Count: 4