Buongiorno a tutti,
per il momento ho lasciato perdere i grafi dedicandomi ad altro. Ho Partorito questo e funziona.
Non è altro che un analizzatore di testi che conta le occorrenze delle parole in un testo. Funziona correttamente:
codice:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;
public class TextAnalyzer {
public static ArrayList<Entry> readWords (Scanner in){
ArrayList<Entry> words = new ArrayList<Entry>();
String w;
intwIndex;
while(in.hasNext()){
w = in.next();
Entry temp = new Entry(w,0);
wIndex= words.indexOf(temp);
if (wIndex==-1){
words.add(temp);
}else{
temp = words.get(wIndex);
}
temp.value +=1;
}
returnwords;
}
public static void main(String[] args){
if (args.length <1){
System.out.println("Devi specificare il nome del file da leggere");
System.exit(0);
}
assert(args.length>=1);
FileReader textReader = null;
try{
textReader = new FileReader(args[0]);
}catch(Exception e){
System.err.println("Non posso aprire il file "+args[0]);
System.exit(0);
}
assert(textReader !=null);
Scanner scanner = new Scanner(textReader);
ArrayList<Entry> word = readWords (scanner);
scanner.close();
try{
textReader.close();
}catch(Exception e){
System.err.println("Non posso chiudere il file "+args[0]);
System.exit(0);;
}
Collections.sort(word);
Iterator<Entry> ai = word.iterator();
while(ai.hasNext()){
Entry t =ai.next();
System.out.println(t);
}
}
}
codice:
public class Entry implements Comparable<Entry> {
public String key;
publicintvalue;
public Entry(String key, int value){
this.key=key;
this.value=value;
}
public int compareTo(Entry other){
return key.compareTo(other.key);
}
public boolean equals(Object other){
if(other==this) returntrue;
if(!(otherinstanceof Entry)) returnfalse;
Entry o = (Entry) other;
return key.equals(o.key);
}
public String toString(){
return (key+" "+value);
}
}
Ho solo un dubbio sul funzionamento. Mi spiego meglio, la classe Entry implementa l'interfaccia Comparable, che effettua un ordinamento, ma in che modo? E poi, i metodi della classe Entry non vengono invocati nel main o in altri metodi della classe TextAnalyzer. Per cui mi viene da pensare che essi si invochino quando creo l'oggetto
codice:
Entry temp = new Entry(w,0)
.
E' corretto quello che dico?? Se no potreste spiegarmelo?
Grazie a tutti

