Home > Software engineering >  why are the words not printing into the new file? java on eclipse
why are the words not printing into the new file? java on eclipse

Time:10-11

this is the code I have. I am printing words with only 5 letters from a document named: words.txt", I am taking those words of 5 letters, and creating a new file named: "five.txt". but when I open the file, the words are not there. here's my code:

     public static void main(String[] args) throws IOException
        {
           
             try (Scanner in = new Scanner("words.txt");
                     
                     PrintWriter out = new PrintWriter("five.txt");)
                 {
                     while (in.hasNext())
                         {
                     
                     String word;
                      
                        word = in.next();
                        if (word.length() == 5)
                        
                        out.println(word);
                        
                         }
                 }
         
         
             catch (IOException e)
                 {
                     
                     System.out.println("Could not read the words: "   e.getMessage());
                     return;  // Exit main now
                 }
         
         
        }   

CodePudding user response:

new Scanner("words.txt")

That doesn't do what you think it does. That will make a scanner for the input 'words.txt'. Not, 'the contents of the file "words.txt"'. No, literally, 'words.txt'. Which has one token, of length 9, which is "words.txt".

You want new Scanner(new File("words.txt")).

  • Related