简体   繁体   English

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

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

How can I add a do while loop so when the FileNotFoundException class is encountered, my user is informed that the file does not exist and provides my user the opportunity to enter another file name? 如何添加do while循环,以便在遇到FileNotFoundException类时,通知我的用户该文件不存在并为我的用户提供输入另一个文件名的机会? This is what I have so far. 这就是我到目前为止所拥有的。 Thanks 谢谢

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

Try something like this... Add a flag 'ok' and do what you do until it gets true. 尝试这样的事情......添加一个标记'ok'并做你做的事情,直到它成为现实。 Than stop the loop. 比停止循环。

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