Try / catch块和if平均程序中的if语句

问题描述 投票:0回答:2

我正在编写一个降雨平均程序。该程序允许用户输入文件名,如果找不到文件,则提示用户重新输入文件名。用户在退出应用程序之前不进行数据处理就进行了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语句有问题吗?

java if-statement try-catch average block
2个回答
0
投票

您的程序有很多问题。这里有一些方法可以帮助您。

  1. 文件inData.dat不存在。请在适当的位置创建它。
  2. 克服该驼峰之后,第40行将出现一个空指针:inFile为空。

我的建议是在诸如Visual Studio Code之类的编辑器中打开它。它会指出很多警告,也可以调试程序。


0
投票

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

  1. try块中行Scanner scan = new Scanner (System.in);的用途是什么?

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

您可能会因为文件已找到而导致do-while结束,并且if-statement的条件为false,因为fileTry <4可能会导致do-while结束。我不明白您为什么会关心找到正确的文件后,尝试使用fileTry计数器。如果用户尝试输入4次文件名,并且在最后一次尝试中输入正确的文件名,则程序将转到该if语句的else部分,并显示“错误”。

© www.soinside.com 2019 - 2024. All rights reserved.