尝试在txt文件中保存数组的克隆但返回NULL

时间:2016-01-04 19:56:15

标签: java arrays text

我正在创建一个应用程序,用于保存txt文件中游戏的用户名和分数。它的概念是,当它向txt文件写入新的用户名和分数时,它应该打开.txt文件,读取它然后复制它,在txt文件中添加一个新的uername和score条目。

我正在考虑使用2个对象数组。第一个是读入的,新的将是写入的,将再有一个条目。

因此,如果player[i]已重新player[i+1],则应使用新条目进行写入。

我正在给你下面的代码!

private Player[] myplayer=null;
private Player[] mynewplayer=null;

//open Players.txt
      int i;
      int n;
      String filename="players.txt";
      try
      {

         FileReader fp=new FileReader(filename);
         BufferedReader bf=new BufferedReader(fp);
         n=Integer.parseInt(bf.readLine());
         myplayer=new Player[n];
         int x=n+1;
         mynewplayer=new Player[x];
         for(i=0;i<n;i++)
         {
             String s=bf.readLine();
             String user="",score="";
             user=s.substring(0,s.indexOf(","));
             s=s.substring(s.indexOf(",")+1);
             score=s;
             myplayer[i]=new Player(user,Double.parseDouble(score));

            for(i=0;i<n;i++)
            {
                     mynewplayer[i]= myplayer[i];
            }
            mynewplayer[x]=new Player(Username,Double.parseDouble(score));
         }

         bf.close();
         fp.close();
        }catch(IOException e)
        {
            System.out.println("Exception was "+e.getMessage());
        }



    //----------------------------------WRITE mytxt!-------------
      n=myplayer.length;
      try
      {
         filename="players.txt";
         FileWriter fp=new FileWriter(filename);
         fp.write(""+n+"\n");
         for(i=0;i<n+1;i++)
           fp.write(""+mynewplayer[i]+"\n");

         fp.close();
        }catch(IOException e)
        {
            System.out.println("Exception was "+e.getMessage());
        }
    //----------------------------------WRITE mytxt!-----------

    //Get on Message
      String s="";
      for(i=0;i<mynewplayer.length;i++)
        s=s+mynewplayer[i]+"\n";
      JOptionPane.showMessageDialog(null,"Players are \n "+s);

问题在于,当它被写入时,它会为null返回mynewplayer。 我想mynewplayer并没有真正接受“myplayer”的条目,但都没有写新的用户名。

编译不会显示任何错误。只需将NULL写入文本文件即可。

问我是否想要有关代码的更多信息!

提前致谢!

2 个答案:

答案 0 :(得分:2)

以下是您的代码的编辑版本,有一些改进,应该对我更改的代码进行评论,解释我的所作所为。

    Player[] myPlayer = null;     // first word uncapitalized, every 
    Player[] myNewPlayer = null;  // other word begins with a capital

    //open Players.txt
    int i, n; // combine the variables into 1 line        
    String filename = "players.txt";

    try {

        FileReader fp = new FileReader(filename);
        BufferedReader bf = new BufferedReader(fp);
        n = Integer.parseInt(bf.readLine());
        // not needed
        //myPlayer = new Player[n];
        // NOT NEEDED int x = n + 1;
        myNewPlayer = new Player[n + 1];

        for (i = 0; i < n; i++) {
            String s = bf.readLine();
            String user, score; // combine variables, doesnt need to initalize them

            String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,

            //user = s.substring(0, s.indexOf(","));
            //s = s.substring(s.indexOf(",") + 1);
            //score = s;
            user = items[0];
            score = items[1];
            // this line below isnt actually needed
            //myPlayer[i] = new Player(user, Double.parseDouble(score));
            // Create a new player clone, dont copy the previous one
            myNewPlayer[i] = new Player(user, Double.parseDouble(score));

        }

        // We've read all the variables from the text file, now we create the last one
        // Since myNewPlayer is (n+1) size, the range of the array is
        // 0 to n
        // the last index will be n                            New Score Variable
        myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));

        bf.close();
        fp.close();
    } catch (IOException e) {
        System.out.println("Exception was " + e.getMessage());
    }

    //----------------------------------WRITE mytxt!-------------
    // This is called a ternary operator
    // it is a 1 line if statement
    // the format is like so
    //   booleanLogic ? trueAnswer Execution : falseAnswer Execution;
    //         if ()  {       true          }else {         false  }
    n = myNewPlayer != null ? myNewPlayer.length : 0;
    // CHANGED HERE - was using the first array rather than second
    // dont need the 1st array
    try {
        filename = "players.txt";
        FileWriter fp = new FileWriter(filename);
        // Dont need "" before the items
        fp.write(n + "\n");
        for (i = 0; i < n; i++) {
            fp.write(myNewPlayer[i] + "\n");
        }

        fp.close();
    } catch (IOException e) {
        System.out.println("Exception was " + e.getMessage());
    }
    //----------------------------------WRITE mytxt!-----------

    //Get on Message
    String s = "";
    for (i = 0; i < myNewPlayer.length; i++) {
        // s += ""; is like doing s = s + "";
        s += myNewPlayer[i] + "\n";
    }

    JOptionPane.showMessageDialog(null, "Players are \n " + s);

答案 1 :(得分:1)

我相信你的问题是:

for(i=0;i<n;i++)
     {
         String s=bf.readLine();
         String user="",score="";
         user=s.substring(0,s.indexOf(","));
         s=s.substring(s.indexOf(",")+1);
         score=s;
         myplayer[i]=new Player(user,Double.parseDouble(score));

        for(i=0;i<n;i++)
        {
                 mynewplayer[i]= myplayer[i];
        }
        mynewplayer[x]=new Player(Username,Double.parseDouble(score));
     }

你有嵌套循环,这很好,但它们使用相同的计数器(变量i)。

所以发生的事情是读取文件的第一行,然后添加到myplayer [0]。但是,不是只将它添加到mynewplayer [0],而是在i上启动另一个循环。这个循环:

        for(i=0;i<n;i++)
        {
                 mynewplayer[i]= myplayer[i];
        }

将第一个播放器复制到mynewplayer [0] ...然后将null复制到其他所有条目中(因为myplayer只填充了firsdt元素)。 问题是在循环完成后,我将等于n,所以当你回到外循环的顶部时,检查$ i

也许你应该做的是:

     for(i=0;i<n;i++)
     {
         String s=bf.readLine();
         String user="",score="";
         user=s.substring(0,s.indexOf(","));
         s=s.substring(s.indexOf(",")+1);
         score=s;
         myplayer[i]=new Player(user,Double.parseDouble(score));
         mynewplayer[i]= new Player(user,Double.parseDouble(score));

     }
     mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));