gpt4 book ai didi

java - 列出名称和出现次数

转载 作者:行者123 更新时间:2023-11-30 08:51:26 24 4
gpt4 key购买 nike

因此任务是读取具有以下名称的文件:

Alice
Bob
James
Richard
Bob
Alice
Alice
Alice
James
Richard
Bob
Richard
Bob
Stephan
Michael
Henry

然后打印出每个名字及其出现的值,例如“Alice - <4>”。
基本上,我让它工作了。我遇到的唯一问题是我的输出中缺少姓氏 (Stephan - <1>),我无法使其正常工作。这可能是因为我使用了 [i-1],但正如我所说,我在这里没有得到正确的解决方案。
好吧,这是我的代码..

package Assignment4;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;

public class ReportUniqueNames {

public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println (" This programm counts words, characters and lines!\n");
System.out.println ("Please enter the name of the .txt file:");

BufferedReader input = new BufferedReader(new InputStreamReader (System.in));

BufferedReader read = null;
String file = "";
String text = "";
String line = "";
boolean unique = true;
int nameCounter = 1;

try {

file = input.readLine();
read = new BufferedReader (new FileReader(file));
while ((line = read.readLine()) != null) {
text += line.trim() + " ";
}

} catch (FileNotFoundException e) {
System.out.println("File was not found.");
} catch (IOException e) {
System.out.println("An error has occured.");
}

String textarray[] = text.split(" ");
Arrays.sort(textarray);

for (int i=0; i < textarray.length; i++) {

if (i > 0 && textarray[i].equals(textarray[i-1])) {
nameCounter++;
unique = false;
}

if (i > 0 && !textarray[i].equals(textarray[i-1]) && !unique) {
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
nameCounter = 1;
unique = true;
} else if (i > 0 && !textarray[i].equals(textarray[i-1]) && unique) {
//nameCounter = 1;
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
}

}

}

}

就是这样..希望你们中的一个能帮助我。

编辑:
哇,这么多不同的方法。
首先感谢大家的帮助。
我会查看您建议的解决方案,并可能从底部重新开始 ;)。
完成后会提醒您。

最佳答案

您可以简单地使用 Map(模拟“Multiset”)来计算单词数:

String textarray[] = text.split(" ");

// TreeMap gives sorting by alphabetical order "for free"
Map<String, Integer> wordCounts = new TreeMap<>();

for (int i = 0; i < textarray.length; i++) {
Integer count = wordCounts.get(textarray[i]);
wordCounts.put(textarray[i], count != null ? count + 1 : 1);
}

for (Map.Entry<String, Integer> e : wordCounts.entrySet()) {
System.out.println("<" + e.getKey() + "> - <" + e.getValue() + ">");
}

关于java - 列出名称和出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30551616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com