Getting null before each line while scanning a txt file

I have a problem reading a txt file and searching for a word / picture using java scanner.util. Currently reading testing and I am getting an empty infront of each line. After this problem, I'm still not sure how to search for a pattern / word in a txt file. I also have to display the string containing the pattern / word.

public class SearchPattern {
   public static void main(String[] args) throws IOException{
      Scanner s = new Scanner(System.in);
      String pattern;
      String filename;
      String[] text = new String[10];
      System.out.println("Enter the filename");
      filename = s.nextLine();
      System.out.println("Enter the pattern you'd like to search");
      pattern = s.nextLine();
      // Print out each line that contains pattern
      // may need an array to store StringS of lines with word
      try{
         s = new Scanner(new BufferedReader(new FileReader(filename)));
         int x = 0;
         while (s.hasNext()) {
            text[x] += s.next();
            x++;
         }
      }
      finally {
         if (s != null) {
            s.close();
         }
      }
      text[0] = "test";
      System.out.println(text[0]);
      for(String txt : text){
         System.out.println(txt);
      }
   }
}

      

+3


source to share


2 answers


s = new Scanner(new BufferedReader(new FileReader(filename)));
        int x = 0;
        while (s.hasNext()) {
            text[x] += s.next();
            x++;
        }

      

What you are doing here is iterating over your array in a way that I assume you are not trying to do.

Right now, for each x position in your array, you write

text[x] = text[x] + s.next();

      

But what you probably want to do is give each position in your array the value of the next scanner value. In code



text[x] = s.next();

      

This can also be written as

        for((int x = 0; s.hasNext(); x++)
            text[x] = s.next();

      

Hope this helps. Good luck!

+2


source


You do:

text[x] += s.next();

      

This means: text[x]

is null

what you adds.next()



Replace it:

text[x] = s.next();

      

+3


source







All Articles