簡體   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