如何添加 do while 循环,以便在遇到 FileNotFoundException 类时,通知我的用户该文件不存在,并为我的用户提供输入另一个文件名的机会?这是我到目前为止所拥有的。谢谢
do
{
// Get a file name from the user.
fileName = JOptionPane.showInputDialog("Enter " +
"the name of a file:");
// Attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null,
"The file was found.");
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null,
"File not found.");
}
///// while(flag+f)
JOptionPane.showMessageDialog(null, "Done.");
System.exit(0);
}
}
最佳答案
尝试这样的事情...添加一个标记“ok”并执行您所做的操作,直到它变为 true。然后停止循环。
boolean ok = false;
do
{
// Get a file name from the user.
fileName = JOptionPane.showInputDialog("Enter " +
"the name of a file:");
// Attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null,
"The file was found.");
ok = true;
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null,
"File not found.");
}
while(ok == false);}
JOptionPane.showMessageDialog(null, "Done.");
System.exit(0);
}
关于java - 如何在我的代码中添加 do while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55962832/