This is my code that I had to use for a question. I am supposed to look for words in the command line in Eclipse by typing java Spell a and getting all word outprinted in the console that starts with a from a local text file. My program terminates for no apparent reason:
import java.util.*;
import java.io.*;
public class Spell {
public static void main (String[] args) throws Exception {
File file = new File("C:\\Users\\Dennis\\words.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNext()) {
String word = fileScanner.next();
if(word.startsWith(args[0])) {
System.out.println(word);
}
}
}
}
If you are running this program as java Spell garfield
then the args[0]
will contain garfield in the file if any word will match with garfield then your print statement will be executed otherwise not.You have to provide run time argument in ecclipse
for running your program and then you will be able to see the actual out put you want.
rightclick in your Class
contaning main method
select run as->run configuration
in the tab (x)=Arguments
give your argument then run and see below is the screen shot for this
In eclipse, right-click on your java file -> Run as -> Run configurations -> Tab Arguments, in programme arguments, enter a. If there is no argument entered, you should get an "ArrayIndexOutOfBoundsException" at the line
if(word.startsWith(args[0])) {
I would suggest putting a break-point on the line
String word = fileScanner.next();
and then Debug. So that you can verify the words scanned by the programme and check if the arg[0] is what you entered.
I have run your programme with words.txt like
asdf bsdf csdf dsdf
and argument c
, it prints out
csdfcorrectly.
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.