java - 如何在我的代码中添加 do while 循环?

标签 java loops while-loop

如何添加 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/

相关文章:

java - Google Ima SDK,播放声音但没有 View

通过读取字符转换为负整数

Java while循环有一定的时间

c++ - 为项目创建一个简单的控制菜单,循环打印提示的次数比预期的多

java - O 符号帮助

java - 有没有运行良好的 Java COM 库?

java - 如果 TRY 错误

c++ - std::string length() 函数如何工作?

python - 在 python 中循环 SQL 查询

java - 循环数组以存储使用前一个元素的值