Java 即使在循环中找不到遇到的文件,如何继续处理? System.out.println(“请输入所需单词:”); 扫描仪扫描=新扫描仪(System.in); String word=scan.nextLine(); String[]数组=word.split(“”); int filename=500; 字符串[]文件名=新字符串[文件名]; int a=0; 尝试 { for(a=0;a

Java 即使在循环中找不到遇到的文件,如何继续处理? System.out.println(“请输入所需单词:”); 扫描仪扫描=新扫描仪(System.in); String word=scan.nextLine(); String[]数组=word.split(“”); int filename=500; 字符串[]文件名=新字符串[文件名]; int a=0; 尝试 { for(a=0;a,java,exception-handling,Java,Exception Handling,将try/catch移动到for循环中 具体来说,您只希望在尝试打开文件时将其包装起来。您应该像这样捕获循环中的异常 System.out.println("Please enter the required word :"); Scanner scan = new Scanner(System.in); String word = scan.nextLine(); String [] array = word.split(" "); int filename = 5

将try/catch移动到for循环中


具体来说,您只希望在尝试打开文件时将其包装起来。

您应该像这样捕获循环中的异常

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);

对于(a=0;a使用
尝试{..}catch()
(请参阅).

您的代码片段似乎不完整,但似乎在for循环中有一个try/catch对。您可能希望在for循环中有另一个try/catch块。您可以让它捕获FileNotFoundException或更一般的异常,并允许循环继续而不中断。

它不继续的原因是异常中断循环,因为它被捕获在循环外部。您需要将try/catch块放置(或移动)在循环内部

 for(a=0; a<filename; a++)
   {
     try{
       Scanner s = new Scanner(file);
     }catch{FileNotFoundException e){ 
      // handle the exception
     }
   }
(a=0;a)的

for(a=0; a<filename; a++) {
    try {
        ...
    } catch (IOException ex) {
        // handle exception
    }
}