首页 > 解决方案 > Try/catch 块和降雨平均程序中的 if 语句

问题描述

我正在编写一个降雨平均程序。该程序让用户输入文件名,如果找不到文件,则提示用户重新输入文件名。用户在应用程序退出而不处理数据之前进行了 4 次尝试,并且应用程序本身就是一个降雨平均程序,就像我说的那样。

package experiment8;
import java.io.*; 
import java.util.Scanner; 
public class Exceptions
{
  static  Scanner inFile;
  public static void main(String[] args) throws IOException
  {
    int fileTry = 0;
    String fileName;
    Scanner inName = new Scanner(System.in);
    System.out.println("Enter file name>");
    fileName = inName.nextLine();
    boolean fileOk;
    do
    {
      fileOk =  false;
      try
        {

          Scanner scan = new Scanner (System.in);
          Scanner file = new Scanner(new File("inData.dat"));
          fileOk = true;
        }
        catch(FileNotFoundException error)
        {

          System.out.println("Reenter file name>");
          fileName = inName.nextLine();
          fileTry++;
        }
    } while (!fileOk && fileTry < 4);
    PrintWriter outFile = new PrintWriter(new FileWriter("outData.dat"));

    if (fileOk && fileTry < 4 )
    {   
        int numDays = 0;
        double average;
        double inches = 0.0;
        double total = 0.0;
        while (inFile.hasNextFloat())
      {
        inches = inFile.nextFloat();
        total = total + inches;
          outFile.println(inches);
          numDays++;
      }

      if (numDays == 0) 
        System.out.println("Average cannot be computed " +
                         " for 0 days."); 
      else
      {
        average = total / numDays;
        outFile.println("The average rainfall over " +  
          numDays + " days is " + average); 
      }
      inFile.close();
    }
    else

      System.out.println("Error");
    outFile.close();
  }
}

我正在尝试编写这个程序,所以当我输入正确的文件名“inData.dat”时,我会得到正确的输出。但是,当我这样做时,在接下来的 3 次中继续提示我重新输入文件名,之后我收到“错误”消息。我的 try/catch 块或 if 语句有问题吗?

标签: javaif-statementtry-catchaverageblock

解决方案


我对您的代码有两个问题。

  1. Scanner scan = new Scanner (System.in);try-block中的行的目的是什么?

  2. 为什么在if (fileOk && fileTry < 4)获取文件的 do-while 块之后有一个 if 语句检查?似乎是多余的。do-while 块检查相同的条件。一旦程序到达这个 if 语句的位置,这个条件就必须满足。如果不是,do-while 将再次运行。

您可能会遇到由于找到文件而导致 do-while 结束的情况,并且此 if 语句的条件为 false 因为 fileTry < 4。我不明白您为什么会关心 fileTry 计数器一旦你找到正确的文件。如果用户尝试输入文件名 4 次并在最后一次尝试时正确,程序将转到此 if 语句的 else 部分并打印“错误”。


推荐阅读