Ошибки при попытке обработать блок catch - PullRequest
0 голосов
/ 07 февраля 2019

Итак, сейчас я пишу программу, которая принимает пользовательский ввод, то есть рецепты, и читает рецепты из другого файла, а затем выводит рецепт в новый файл с именем ShoppingList.txt.Я пытаюсь создать файл, но когда я пытаюсь скомпилировать программу, я получаю эту ошибку.RecipeList.java:80: ошибка: исключение FileNotFoundException никогда не генерируется в теле соответствующего catch оператора try (FileNotFoundException e) Может кто-нибудь помочь мне отладить его.Спасибо!

//Prasanth Dendukuri
// 2/5/18
// RecipeList.java


import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;

public class RecipeList
{
    private Scanner terminal; // to read in input from kb
    private Scanner reader; // to read in from the text fi;e
    private String inFileName; // name of file to read from
    private String outFileName; // name of file to output to
    private String[] recipeList; // array that contains the recipes
    private String[] ingredients; // array that contains ingredients for each recipe
    private PrintWriter output; // print writer for writing to output file
    private String input; // to accept input and store in this variable
    private int numInput; // num of recipes entered
    private Scanner file; // scanner used for reading in from file

    public RecipeList()
    {
        terminal = new Scanner(System.in);
        inFileName = new String("Recipes.txt");
        outFileName =  new String("ShoppingList.txt");
        recipeList =  new String[20];
        ingredients = new String[20];
        input = new String(" ");
        output = null;
        numInput = 0;

    }

    public static void main(String[] args)
    {
        RecipeList rl = new RecipeList();
        rl.run();
    }

    // calls all methods and prints blank lines
    public void run() 
    {
        System.out.print("\n\n\n");
        getInput();
        openRecipes();
        makeFile();
        readFile();
        output.close();
    }

    // gets input of recipes until 'quit' is entered
    public void getInput()
    {
        while(!input.equalsIgnoreCase("quit"))
        {
            System.out.print("Type in a recipe.Type quit to end the program--> ");
            input = terminal.nextLine();

            if(!input.equalsIgnoreCase("quit"))
            {
                recipeList[numInput] = input;
                numInput++;
            }
        }

    }

    //opens RecipeList and handles exceptions 
    public void openRecipes()
    {
        File inFile = new File(inFileName);
        try
        {
            file = new Scanner(inFileName);
        }
        catch(FileNotFoundException e)
        {
            System.err.println("ERROR. Could not read/find file.");
            System.exit(1);
        }
    }

    // makes ShoppingList.txt and handles exceptions 
    public void makeFile()
    {
        File outFile = new File(outFileName);

        try
        {
            output = new PrintWriter(outFile);
        }
        catch(IOException e)
        {
            System.err.println("ERROR. Could not read/find file.");
            System.exit(2);
        }
    }

    public void readFile()
    {
        String directions = new String("");

        while(file.hasNext())
        {
            directions = file.next();
        }

        output.print(directions);

    }

}

            ^

Ответы [ 2 ]

0 голосов
/ 07 февраля 2019

Проблема связана с методом openRecipes ().Вы пытаетесь обработать исключение FileNotFoundException, в то время как оно не генерируется классом сканера.Используйте объект файла, который вы создали в классе сканера, и он начнет работать.Скопируйте и вставьте следующий код.

public void openRecipes()
    {
        File inFile = new File(inFileName);
        try
        {
            file = new Scanner(inFile);
        }
        catch(FileNotFoundException e)
        {
            System.err.println("ERROR. Could not read/find file.");
            System.exit(1);
        }
    }
0 голосов
/ 07 февраля 2019

С этим кодом смотрите мои комментарии

    File inFile = new File(inFileName);
    try
    {
        file = new Scanner(inFileName);  
        // you are trying to use the Scanner using a `String`
        // this does not throw an Exception, hence the compile error
        // I think you want to use
        // public Scanner(File source) which throws a FileNotFoundException
        // so change to use instead
        file = new Scanner(inFile);  
    }
    catch(FileNotFoundException e)
    {
        System.err.println("ERROR. Could not read/find file.");
        System.exit(1);
    }
...