Reputation: 259
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String [] array = word.split(" ");
int filename = 500;
String[] fileName = new String [filename];
int a = 0;
try
{
for(a=0; a<filename; a++)
{
File file = new File("C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a + ".txt");
System.out.println("File = abc" + a + ".txt");
for( int i=0; i<array.length; i++)
{
System.out.println(array[i]);
int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext())
{
totalCount++;
if (s.next().equals(array[i])) wordCount++;
}
System.out.println("Word count: " + wordCount);
System.out.println("Total count: " + totalCount);
System.out.printf("Term Frequency: %8.4f", (double) wordCount / totalCount);
the output :
File = abc4.txt
a Word count: 2 Total count: 119 Term Frequency: 0.0168
about Word count: 0 Total count: 119 Term Frequency: 0.0000
the Word count: 3 Total count: 119 Term Frequency: 0.0252
File = abc5.txt a Word count: 4 Total count: 141 Term Frequency: 0.0284
about Word count: 0 Total count: 141 Term Frequency: 0.0000
the Word count: 2 Total count: 141 Term Frequency: 0.0142
File = abc6.txt
a File is not found
after the a specific file is not found, the code stops. How to make it to proceed to other file ? This code has 2 additional files to process but it stops when encountered file not found. Any advices ?
Upvotes: 0
Views: 765
Reputation: 743
The reason it is not continuing on is the exception breaks the loop since it is caught outside of the loop. You need to put (or move) the try/catch block inside of the loop.
for(a=0; a<filename; a++) {
try {
...
} catch (IOException ex) {
// handle exception
}
}
Upvotes: 0
Reputation: 7375
Your code snippet appears incomplete, but it looks like you have a try/catch pair around the for loop. You might want another try/catch block inside the for loop. You can have it catch FileNotFoundException or a more general exception and allow the loop to continue without breaking.
Upvotes: 0
Reputation: 34179
You should catch for the exception inside your loop like so
for(a=0; a<filename; a++)
{
try{
Scanner s = new Scanner(file);
}catch{FileNotFoundException e){
// handle the exception
}
}
Upvotes: 1
Reputation: 76918
Move your try/catch inside your for loop.
Specifically, you want to only wrap it around the attempt to open the file.
Upvotes: 0