繁体   English   中英

如何在代码中添加do while循环?

[英]How can I add a do while loop to my code?

如何添加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'并做你做的事情,直到它成为现实。 比停止循环。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM