使用 FileWriter 变量作为方法的参数

Using FileWriter variable as a parameter for a method

我正在尝试创建一个接受用户输入并将其输入到文件中的程序。我想要一个部分来设置所有内容以及一种实际记录所有内容的方法。当我尝试将 FileWriter writer 用作参数时,我 运行 遇到了问题。它给我错误,例如 "FileWriter cannot be resolved to a variable"。我该如何解决?有没有更好的方法来使用 FileWriter 和 Method ListTasks?

public class TaskCreate 
{
static Scanner taskInput = new Scanner(System.in);
static Scanner userContinue = new Scanner(System.in);
static String decision = "yes";
static int i = 1;

public static void Create() throws IOException 
{   
    try
    {
        File tasklist = new File("tasklist.txt");
        tasklist.createNewFile();
        // creates a FileWriter Object
        if(tasklist.equals(true))
        {
            FileWriter writer = new FileWriter(tasklist);
        }
        else
        {
            FileWriter writer = new FileWriter(tasklist, true);
        }

//***********************************************
         //I get the "FileWriter cannot be resolved to a variable" here.
         //I also get the "Syntax error on token "writer", delete this              //token" here
        ListTasks(FileWriter writer);
//***********************************************
        taskInput.close();
        userContinue.close();
    }
    catch(Exception e)
    {
    System.out.print("You did something wrong");    
    }
}
//****************************************************************
//Why does it work here and not up there?
public static void ListTasks(FileWriter writer) throws IOException
//*********************************************************************
{
    while(decision.equals("yes"))
    {                   
        System.out.print("Please enter a task: ");
        String task = taskInput.nextLine();

            // Writes the content to the file
        writer.write(i + " " + task + System.getProperty( "line.separator" ));

        System.out.print("Would you like to enter another task? yes/no: ");
        decision = userContinue.nextLine();
        System.out.print(System.getProperty( "line.separator" ));

        ++i;
    }
    writer.flush();
    writer.close();
}   
}

首先,在这里您在 {} 块中创建了局部变量 writer,它一旦执行就会超出范围。

     // creates a FileWriter Object
        if(tasklist.equals(true))
        {
            FileWriter writer = new FileWriter(tasklist);
        }
        else
        {
            FileWriter writer = new FileWriter(tasklist, true);
        }

改写成这样:

    FileWriter writer = null;

    if(tasklist.equals(true))
    {
        writer = new FileWriter(tasklist);
    }
    else
    {
        writer = new FileWriter(tasklist, true);
    }

然后,您写道:

ListTasks(FileWriter writer);

这是不正确的,你应该只写一个变量的名称而不是它的类型,即:

    ListTasks(writer);