我正在处理的程序询问用户是否是新用户,如果用户是新用户,则必须为他们的个性化音乐数据库分配他们自己的txt文件。 txt文件应标有用户名。我尝试使用int
变量来标记txt文件,因为用户数量未知。这就是我到目前为止所做的:
System.out.println ("Are you a new user?(y/n)");
response = (stdin.readLine ());
if (response.equals ("Y"))
{
System.out.println ("What is your name?");
name [0] = (stdin.readLine ());
BufferedWriter writer = new BufferedWriter (new FileWriter ("" + name + ".txt"));
System.out.println ("How many songs would you like to enter?");
number = Integer.parseInt (stdin.readLine ());
for (int i = 0 ; i < number ; i++)
{
System.out.println ("What is the artist of the song you would like to add?");
artist [i] = (stdin.readLine ());
System.out.println ("What is the genre of the song you would like to add?");
genre [i] = (stdin.readLine ());
System.out.println ("What is the name of the song you would like to add?");
songs [i] = (stdin.readLine ());
count++;
}
for (int i = 0 ; i < number + count ; i++)
{
writer.write ("" + artist [i] + "");
writer.newLine ();
writer.write ("" + genre [i] + "");
writer.newLine ();
writer.write ("" + songs [i] + "");
writer.newLine ();
}
writer.close ();
}
else if (response.equals ("y"))
{
System.out.println ("What is your name?");
name [0] = (stdin.readLine ());
BufferedWriter writer = new BufferedWriter (new FileWriter ("" + name + ".txt"));
System.out.println ("How many songs would you like to enter?");
number = Integer.parseInt (stdin.readLine ());
for (int i = 0 ; i < number ; i++)
{
System.out.println ("What is the artist of the song you would like to add?");
artist [i] = (stdin.readLine ());
System.out.println ("What is the genre of the song you would like to add?");
genre [i] = (stdin.readLine ());
System.out.println ("What is the name of the song you would like to add?");
songs [i] = (stdin.readLine ());
count++;
}
for (int i = 0 ; i < number + count ; i++)
{
writer.write ("" + artist [i] + "");
writer.newLine ();
writer.write ("" + genre [i] + "");
writer.newLine ();
writer.write ("" + songs [i] + "");
writer.newLine ();
}
writer.close ();
}
答案 0 :(得分:0)
如果您想为新用户创建一个新文件,请使用
File file = new File(name+ ".txt");
if(! file.exists())
{
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter (new FileWriter (file));
也可以使用
response.equalsIgnoreCase("Y")
避免重复代码