我有一个任务,我必须创建3个类Oblig6(主要方法),Word(Ord)和Wordlist(Ordliste)。我必须使用单词class来找到单词在文本中重复的次数。使用词类查找给定词的计数
我在制定下面的段时遇到了问题。我需要单词class来创建给定单词的新对象,如果它已经在单词列表(ArrayLis ordliste)中,然后下一次它在文本中找到同一单词时,它必须将该特定单词的总数加1由Ord(String s)定义的对象。我知道每次发现单词列表中的单词时,我都会创建一个新对象,我需要一个关于如何正确表达它的建议。 这是我的代码。
wordlist类的主要问题是在void fraOrdtilOrdliste中。
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class Ordliste {
private ArrayList<String> ord = new ArrayList<String>();
private ArrayList<String> ordliste = new ArrayList<String>();
private int i = 0;
private int totalord = 0;
private int antallforekomster = 0;
// Reads the provided txt file and puts the words into a word list
void lesBok(String filnavn) throws Exception {
File file = new File(filnavn);
Scanner innlestfil = new Scanner(file);
while (innlestfil.hasNextLine()) {
ord.add(innlestfil.nextLine());
}
}
// Reads ord arryalist and compares the words to ordliste arraylist, adds them if they are not inn it all ready
//If they are there, crates a new Ord(String s)object of that words and adds to amount.
void fraOrdtilOrdliste() {
ordliste.add(ord.get(i));
for (i=0;i<ord.size();i++) {
Boolean unik = true;
for (int j = 0; j<ordliste.size();j++) {
if (ordliste.get(j).equalsIgnoreCase(ord.get(i))) {
unik = false;
new Ord(ordliste.get(j)).oekAntall();
}
}
if (unik) {
ordliste.add(ord.get(i));
}
}
}
// Using the Ord class as a counter for this method. If the word is registerd beforhand it will add 1.
void leggTilOrd(String s) {
for (i = 0; i < ord.size(); i++) {
if (ord.get(i).equalsIgnoreCase(s)) {
ord.add(i, s);
System.out.println("Suksess");
} else if (!ord.get(i).equalsIgnoreCase(s)) {
new Ord(s).oekAntall();
System.out.println("Antall okt");
return;
}
}
}
// Searches for the word in the wordlist and returns null if it does not exist.
Ord finnOrd(String s) {
for (i = 0; i < ord.size(); i++) {
if (!s.equalsIgnoreCase(ord.get(i))) {
System.out.println("null");
return null;
} else if (s.equalsIgnoreCase(ord.get(i))) {
System.out.println("Fant ordet");
}
}
return null;
}
// Prints out the total amount of words in the word list.
int antallOrd() {
for (i = 0; i < ordliste.size(); i++) {
totalord++;
}
System.out.println("Antall ord i ordlisten er: " + totalord);
return totalord;
}
// Counts the total amounts of a word in the word list.
int antallForekomster(String s){
antallforekomster= new Ord(s).hentAntall();
System.out.println("Ordet forekommer " + antallforekomster + " ganger");
return antallforekomster;
}
她是单词班。
我不明白。为什么不把整个文本传递给静态方法中的单词类,该静态方法返回要计数的字的地图? – algorithmic 2014-11-04 20:18:47
我忘了提及我对编程很陌生。如果你正在谈论为什么我不使用hashmap,那是因为我不被允许。 – liptonvice 2014-11-04 20:22:23