I need to display first word from each line.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alex1984
    New Member
    • Oct 2015
    • 8

    #1

    I need to display first word from each line.

    Hey guys I'm using dictionary.txt file and need to display first word from each line so I can then randomly pick 100 of them and find word definitions for it.
    I'm having problem with displaying first words, for some reaso I can only display words starting with 'S'.
    Here is what I have so far:

    Code:
    public static void main(String args[])
    	  {
    	  try{
    	  // Open the file that is the first 
    	  // command line parameter
    	  FileInputStream fstream = new FileInputStream("dictionary.txt");
    	  // Get the object of DataInputStream
    	  DataInputStream in = new DataInputStream(fstream);
    	  BufferedReader br = new BufferedReader(new InputStreamReader(in));
    	  String strLine;
    	  //Read File Line By Line
    	  while ((strLine = br.readLine()) != null)   {
    
    	      String[] delims = strLine.split("  ");
    	      String first = delims[0];
    	     
    	      for(int i = 0; i < delims.length-1; i++ )
    	      {
    	    	  System.out.println(delims[i]);
    	      }	      
    	  }
    	  //Close the input stream
    	  in.close();
    	    }catch (Exception e){//Catch exception if any
    	  System.err.println("Error: " + e.getMessage());
    	  }
    	  }
    Last edited by Rabbit; Oct 26 '15, 05:42 AM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Can you please list the content of the file?
    And also the output you get?

    By the way,
    your for-loop in line 17 is probably wrong: you are skipping the last splitted part.

    correct:
    Code:
              for(int i = 0; i < delims.length; i++ )
    Maybe you want to split by a single space, but you are actually splitting by two spaces. So if you don't have 2 spaces in a line, then everything goes into index 0 of the splitting array (which you are skipping to show for some unknown reason as discussed above.)

    Comment

    • alex1984
      New Member
      • Oct 2015
      • 8

      #3
      There are 2 spaces after each word. The content of the file is dictionary: word, then two spaces and definition (all in one line). I'm not at home right now so don't have access to that dictionary.txt file.

      Comment

      • chaarmann
        Recognized Expert Contributor
        • Nov 2007
        • 785

        #4
        If the dictionary.txt file is large, then just copy the first 10 lines from it.
        Also, after fixing the for loop as described above, does the problem still exist?

        Comment

        Working...