I am using BufferedReader to read Word objects from a file, but it turns out BufferedReader is designed so that it can only read in Strings, instead of a user defined object.
A Word object in this case is a string, just not defined as a String
In other words, how can I convert str2[i] into a Word object from a String in order to enqueue it?
This is because the enqueue method takes in Word objects.
public static void main(String[] args) {
WordPriorityQueue x = new WordPriorityQueue();
File file = new File("file goes here");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st = br.readLine()) != null) {
String str1 = br.readLine();
String str2[] = str1.split(" ", 500);
int i = 0;
while(str2[i] != null) {
//How can I convert the string str2[i] to a Word object?
x.enqueue(str2[i]); //Doesn't work for Strings
i++;
}
}
}
I don't think that you are using the javax.speech.Word
object. I suppose that Word is a your class.
To create a new object, Java provides constructors.
Def
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
So, in your code you have to create a Word Object using the constructor for each items.
public static void main(String[] args) throws IOException {
//List that contains all words
List<Word> wordsList = new ArrayList<>();
//Create the scanner
File file = new File("file goes here");
Scanner sc = new Scanner(file);
while( sc.hasNextLine() ) {
String[] lineSplitted = sc.nextLine().split(" "); //add 500 as limit
for (i=0; i<lineSplitted.length; i++) {
//Call constructor
wordsList.add(new Word(lineSplitted[i])
}
}
sc.close()
}
In your Word class, add a constructor that as argument wants a string.
public class Word {
private String word;
public Word(String word) {
this.word = word;
}
//Other methods, getter, setter, etc...
}
A the end, you will have a java.util.List
of Word
objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.