我正在尝试创建一个程序,它接受用户输入并将其输入到文件中。我想要一个部分来设置所有内容和一个实际记录所有内容的方法。当我尝试将FileWriter writer用作参数时,我遇到了一个问题。它给了我错误,例如" FileWriter无法解析为变量"。我该如何解决?有没有更好的方法来使用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();
}
}
答案 0 :(得分:1)
首先,在这里你在{}块中创建局部变量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);