gpt4 book ai didi

java - 即使在循环中找不到文件,如何继续处理?

转载 作者:行者123 更新时间:2023-12-01 15:55:09 24 4
gpt4 key购买 nike

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

输出:

文件 = abc4.txt

一个字数:2总数量:119词频:0.0168

关于字数:0总数量:119词频:0.0000

的字数:3总数量:119词频:0.0252

文件 = abc5.txtA字数:4总数量:141词频:0.0284

关于字数:0总数量:141词频:0.0000

的字数:2总数量:141词频:0.0142

文件 = abc6.txt

一个找不到文件

找不到特定文件后,代码停止。如何让它继续处理其他文件?此代码有 2 个附加文件要处理,但在遇到未找到文件时会停止。有什么建议吗?

最佳答案

你应该像这样捕获循环内的异常

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

关于java - 即使在循环中找不到文件,如何继续处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5234208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com