Hello all, I am trying to find all occurences of a letter in a word. If the letter is present in the word, then I save it to a String. For example here is the text: Hello World, my name is godzab. I search the text, and if there is the letter 'o' in the word, then I add it to the String. The problem is, when I try this, all I get is hello stored in my String. Am I doing the search wrong, or is there a better way to do this. Here is my code:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FindWord{

   public static void main(String[] args) throws IOException{
      String result = "";
      String read = "";
      Scanner s = new Scanner(new File("test.txt"));
      while(s.hasNext()){
         read = s.next();
         if(read.indexOf('o') != -1){
            result = read +"\n";
         }
      }
      s.close();
      System.out.println(result);

   }

}

Here is the test.txt file:

hello world my name is bob.
The nextLine is read.

EDIT: in the string reuslt, and word bob is only stored.

I found out the answer to my own problem. On line 13, insead of reuslt = read + \n, it needs to be result += read + '\n'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.