0

我正在开发的程序会询问用户他们是否是新用户,如果用户是新用户,您必须为他们的个性化音乐数据库分配他们自己的 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 ();
}
4

1 回答 1

0

如果您想为新用户创建一个新文件,请像这样使用

 File file = new File(name+ ".txt");

    if(! file.exists())
    {
        file.createNewFile();
    }
    BufferedWriter writer = new BufferedWriter (new FileWriter (file));

也使用

response.equalsIgnoreCase("Y")

避免重复代码

于 2013-04-12T17:50:54.620 回答