Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why are the words not printing into the new file? java on eclipse

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
                 }
         
         
        }   

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading