gpt4 book ai didi

java - 遍历 try/catch block ?

转载 作者:搜寻专家 更新时间:2023-11-01 03:06:31 25 4
gpt4 key购买 nike

我正在尝试编写如下所示的 try catch block ,但将其放在循环中。我的问题是,当我将它放入 while 循环时,它会运行 x 次。我希望它在第一次尝试成功时停止。但可以选择最多运行 3 次。

    try {

myDisplayFile();

} catch (FileNotFoundException e1) {
System.out.println("could not connect to that file..");

e1.printStackTrace();
}

public static void myDisplayFile() throws FileNotFoundException{
Scanner kin = new Scanner(System.in);
System.out.print("Enter a file name to read from:\t");
String aFile = kin.nextLine();

kin.close();

Scanner fileData = new Scanner(new File(aFile));
System.out.println("The file " + aFile + " contains the following lines:");

while (fileData.hasNext()){
String line = fileData.next();
System.out.println(line);
}//end while
fileData.close();
}

最佳答案

int max_number_runs = 3;
boolean success = false;

for( int num_try = 0 ; !success && num_try < max_number_runs ; num_try++ )
{
try
{
/* CODE HERE */
success = true;
}
catch( Exception e )
{

}
}

关于java - 遍历 try/catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414546/

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