Re: Extending the code
Matt wrote:
I have the following code but i want to add a function which will allow
me to count the number of vowels in the text file. I was wondering if
anyone would be willing to give me some help with this
[CODE]
import java.io.*;
import java.util.*;
public class App {
//Create BufferedReader class instance
public static InputStreamReader input = new
InputStreamReader(System.in);
public static BufferedReader keyboardInput = new BufferedReader
(input);
public static void main(String[] args) {
int[] lengths = new int[100]; //Runtime error if the file contains a
Please excuse me while I go throw up.
*BLETCH!*
Ah. Much better.
Okay. Where were we?
Ah yes, we were right where I'm supposed to recommend you use a
Map<Integer, Integer> in place of that array to get a nice, sparse
representation that doesn't ever blow up just because one day you use a
really big integer as a key. Hell, you can even use Long if Integer
isn't big enough, or BigInteger if you want it to work with a really
REALLY really big integer!
Actually, I've generally only got two uses for arrays except in very low
level heavily encapsulated code. One is a literal array fed to a
collection constructor. The other is a one-element array, a useful trick
for turning anything mutable whatever the class designer originally had
in mind. This includes turning things mutable that the *language*
designer didn't plan on --
class MyRuntimeException extends RuntimeException { }
public String fooBar () {
final int[] counter = new int[1];
counter[0] = 0;
try {
doSomething(new someInterface() {
public void someMethod() {
System.out.println("Yes! An honest-to-God" +
closure -- in Java!");
counter[0]++; // Did I really just increment
// that counter?
throw new MyRuntimeException("Let's" +
" return this string from fooBar!");
}
}
} catch (MyRuntimeException e) {
return e.getMessage(); // Could have had exception wrap any
// object.
}
// do other stuff
return someOtherString;
}
(OK, the "closure" return-from-lexical-scope only works if nothing
between doSomething and someMethod catches a generic RuntimeException,
Exception, or Throwable without rethrowing, which would be bad practise
anyway. So sue me. It's still damn close, albeit liberally sprinkled
with Java's own unique brand of syntactic salt.)