I've been working hard at this code to make a Markov Language Generator but am running into some compilation errors as of late specifically on line 107. I am using the Sedgewick and Wayne library if that helps.
word is a Vector, which means that word.get(j) returns an Object, and you can't assign that to an int variable.
The best solution to this would be to use a generic collection: Vector<Integer> (or even better, ArrayList<Integer>, since Vectors are pretty obsolete now). That way it will make sure that you only put integers into the Vector, and you can assign it to an int when you extract a value. You're using generics elsewhere in the code, so I suspect you just forgot to use them here?
I'm not fully getting how to implement ArrayList<Integer> as I haven't learned about this yet. I get what you're saying about word.get(j) returning and object that can't be assigned but I'm not sure where to use the ArrayList<Integer> code
thanks for the help you've given me so far I do really appreciate it.
Well, ArrayList is a modern replacement for Vector. To use that, you'd just replace every use of Vector with ArrayList.
To get rid of your particular problem, change line 88 to:
but you could equivalently use:
In fact, there's an even better way:
This is what's known as "programming to an interface". Both Vector and ArrayList implement the List interface. The advantage of this style is that you can interchange between different types of List whenever you want. Similarly, you could rewrite line 68 more flexibly as:
Matthew Brown wrote:Well, ArrayList is a modern replacement for Vector. To use that, you'd just replace every use of Vector with ArrayList.
Actually, that will only work if the code doesn't make use of any Vector-specific methods, such as elementAt(); but I certainly agree that it's worth making the change.
Here's how you can go about tracking down the error:
The only way line 97 can throw a NullPointerException is if v is null (then calling v.size() will throw it). You can confirm that by printing out the value just before, if you want (or stepping through with a debugger if you're using an IDE).
So then look at where v is assigned. That's on line 95. m.get(last) must be returning null. So next, find out what last is at that point. It's "" the first time round the loop, but I don't know if it's erroring the first time round - you need to find that out. Once you've tracked down the offending value of last, there are three possible sources of the error:
- You shouldn't be calling m.get(last) with that value of last - m doesn't contain a value for that value of last, but it should do
- Calling it is OK, but you need to be able to cope with it returning null
You'll have to decide which of those it is, as you're the one who knows what the program is trying to do.
(I'd also suggest indenting your code properly, as it will be much easier to follow!)
Don't get me started about those stupid light bulbs.