9 Replies Latest reply: Aug 5, 2009 4:12 PM by 796440 RSS

    String reverting to 'null'

    807588
      Hello. I've been working on the following problem for the last few hours, and it's driving me mad! It seems fairly straightforward: using a buffered reader and a string builder, I'm writing the contents of a text file to a string. The text file is being read and appended to the string as follows (note that getScore is my StringBuilder:
      BufferedReader br = new BufferedReader (new FileReader(songName));
      
      try
      {
           String line = "";
           while ((line = br.readLine()) != null)
           {
                getScore.append(line);
                System.out.println("Line 1 = " + line);
           }
      System.out.println("Line 2 = " + line);
      When I check the console, I see the following:
      Line 1 = 0
      Line 2 = null
      I can't understand why my string is reverting to null as soon as I leave the while loop. I'm fairly new at Java, so it may well be something obvious.

      Thanks,

      Alex


      My entire code (altered slightly to be compilable without the other classes) is below:
      //package dguitar.statistics;
      
      import java.io.*;
      //import dguitar.gui.DGuitar;
      
      public class highScore
      {
           public String songName = "filename.gp3.txt";
           public String tempScore;
           public int newScore = 1000;
           public int oldScore;
           
           public void setOldScore(int score)
           {     
                this.oldScore = score;
           }
           
           public void setNewScore(int score)
           {
                this.newScore = score;
           }
           
           public int getOldScore()
           {
                return oldScore;
           }
           
           public int getNewScore()
           {
                return newScore;
           }
      
                     
           public String reader(String songName)
           {
                StringBuilder getScore = new StringBuilder();
                try
                {
                     File scoreFile = new File (songName);
                     
                     if (scoreFile.createNewFile())
                     {
                          BufferedWriter brNewFile = new BufferedWriter(new FileWriter(songName));
                          brNewFile.write("0");
                          brNewFile.close();
                          System.out.println("'0' has been written to the new file");
      
                     }
           
                     BufferedReader br = new BufferedReader (new FileReader(songName));
      
                     try
                     {
                          System.out.println("TRY");     
                          String line = "";
                          while ((line = br.readLine()) != null)
                          {
                               getScore.append(line);
                               System.out.println("Line in while = " + line);
                          }
      
                          System.out.println("Line after while = " + line);
                          int old = Integer.parseInt(line);
                          setOldScore(old);
      
                     }
                     //System.out.println("END OF TRY");
                     finally 
                     {
                          br.close();
                     }               
                }
                catch (IOException ex)
                {     
                     ex.printStackTrace();
                }
                return getScore.toString();
           }
           
           public void writer(int oldScore, int newScore)
           {
      
                StringBuffer sb = new StringBuffer();
                
                if (oldScore < newScore)
                {
                     String fileName = "highScores\\" + songName + ".txt";
                     
                     try
                     {
                          FileInputStream fis = new FileInputStream(fileName);
                          BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                          String line = "";
                          String oldtext = "";
      
                          String strNewScore = Integer.toString(newScore);
                          String strOldScore = Integer.toString(oldScore);
                          
                          while((line = reader.readLine()) != null)
                          {
                               line = line.replaceAll(strOldScore,strNewScore);
                               sb.append(line+"\r\n");
                          }
                          reader.close();
                          
                          BufferedWriter out = new BufferedWriter (new FileWriter(fileName));
                          out.write(sb.toString());
                          out.close();
                          System.out.println("High score changed to " + strNewScore);
                     }
                     catch (IOException ioe)
                     {
                          ioe.printStackTrace();
                     }
                }
                else{ System.out.println("High score not changed. Still = " + oldScore); }
           }
           
           public static void main (String args [])
           {
                highScore h = new highScore();
                h.tempScore = h.reader("highScores\\" + h.songName +".txt");
                h.oldScore = Integer.parseInt(h.tempScore);
                h.writer(h.oldScore, h.newScore);
           }
      }
        • 1. Re: String reverting to 'null'
          796440
          Obivously it will be null after the loop. How else would you break out of the loop? line = null is the way you break out of the loop
          // in while loop
          line = br.readLine(); // line = "0"
          System.out.println("Line 1 = " + line): // S.o.p. "Line 1 = 0"
          // now back to while test
          while ((line = br.readLine()) // line = null
            != null // while line != null --> while null != null
          // line is null, so break out of loop
          System.out.println("Line 2 = " + line); // "Line 2 = null"
          Edited by: jverd on Aug 5, 2009 12:33 PM
          • 2. Re: String reverting to 'null'
            807588
            o/p is explained correctly above ...
            I guess , you want to echo getScore there ....
            • 3. Re: String reverting to 'null'
              DrClap
              Your loop is explicitly designed to exit when that variable becomes null -- look at it carefully -- so it shouldn't be surprising that after the loop exits, that variable is null.

              Note that the variable is assigned to in the while-clause, so that's where it becomes null. You won't ever see it having the value null inside the body of the loop.

              The code you posted is a common idiom for reading a text file one line at a time, but I remember the first time I saw it, I didn't like it much. Besides the chance of getting the parentheses in the wrong place, it just didn't seem an obvious way of implementing an n-and-a-half loop. But it's an idiom so you might as well do it that way.

              By the way, why is this a problem? Apart from the understanding, I mean.
              • 4. Re: String reverting to 'null'
                807588
                You know sometimes, when you've been staring at something all day, and you just need someone else to point out you're being an idiot? Well...yeah. Thanks!

                Alex
                • 5. Re: String reverting to 'null'
                  796440
                  uk_mal wrote:
                  You know sometimes, when you've been staring at something all day, and you just need someone else to point out you're being an idiot?
                  Been there!
                  • 6. Re: String reverting to 'null'
                    807588
                    Here is how I get a string from a Reader:
                    Reader reader = new FileReader("<insert filename here>");
                    StringBuffer buffer = new StringBuffer("");
                    int c;
                    while((c = reader.read()) != -1) buffer.append((char) c);
                    String text = buffer.toString();
                    • 7. Re: String reverting to 'null'
                      796440
                      privatevoid wrote:
                      Here is how I get a string from a Reader:
                      Reader reader = new FileReader("<insert filename here>");
                      StringBuffer buffer = new StringBuffer("");
                      int c;
                      while((c = reader.read()) != -1) buffer.append((char) c);
                      String text = buffer.toString();
                      That's a sucky way to do it. You're doing a bunch of work that the Reader can do for you. Plus it's not a clear expression of your intent. Reading by lines is more natural.

                      Edited by: jverd on Aug 5, 2009 2:05 PM
                      • 8. Re: String reverting to 'null'
                        807588
                        I'm not sure whether reading lines will preserve the "\n" at the end.

                        There also isn't a read line method in the Reader class.

                        Edited by: privatevoid on Aug 5, 2009 5:10 PM
                        • 9. Re: String reverting to 'null'
                          796440
                          privatevoid wrote:
                          I'm not sure whether reading lines will preserve the "\n" at the end.
                          You don't generally need to when reading a text file.

                          >
                          There also isn't a read line method in the Reader class.
                          There is in BufferedReader.