-1

I was trying to read some words from a text file and then arrange them into descending array. I reached the point where I read the words successfully,stored the words in a array, and when I went ahead to arrange it into descending form I noticed that my array also contained some null values. When I tried to remove the null values using (complete code below) Arrays.stream(w.words).filter(x->x != null).toArray(); , it still didn't worked. After trying for quite some time now I think I need some help here. Code,text file and output at this stage is as follows: `

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;

public class Practise {

    private Scanner fp;
    private Scanner scanLine;
    private String[] words = new String[6] ;

    int count;
    String temp;
    String [][] samewords;
    int size;
    String[] words_sorted;    

    public Practise() {
        openFile();
        readFile();   
        printa();
    }

    private void openFile() {
        try {
            fp = new Scanner(new File ("D:\\workspace\\file.txt"));   
        }
        catch (Exception e) {
            System.out.println("File does not exist");
        }
    }

    private void readFile() {
        try {    
            count = 0;    
            while (fp.hasNextLine()) {
                String strLine = fp.nextLine();    
                scanLine = new Scanner(strLine);        
                words[count] = scanLine.next();    
                System.out.println("Here2"+words[count]);    
                System.out.println();
                count++;       
            }       
        }
        catch (Exception e) {           
            System.err.print("Error: " + e.getMessage());
        }
    }

    private void printa() {         
         try (BufferedReader br = new BufferedReader(new FileReader("D:\\workspace\\file.txt"))) {
             size = findLongestWords();
             samewords = new String[size][size];
             String line;
             int i = 0;
             String [] temp;
             while ((line = br.readLine()) != null) {
                 temp = line.split(",");                       
                 for (int j = 0; j < samewords[i].length; j++) {
                     samewords[i][j] = temp[j];
                     System.out.println(samewords[i][j]);
                 }
                 i++;
             }                  
             //System.out.println(answers[1][2]);
         } catch (IOException e) {
             e.printStackTrace();
         } 
    }

    public int findLongestWords() throws FileNotFoundException {

        int longest_word = 0;
        int current;
        BufferedReader sc = new BufferedReader(new FileReader("D:\\workspace\\file.txt"));    
        String li;
        String[] tr;    
        try {
            while ((li = sc.readLine())!= null ) {
                tr = li.split(",");
                current = tr.length;                      
                if (current > longest_word) {
                    longest_word = current;
                }    
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("\n"+longest_word+"\n");
        return longest_word;
    }
    private  String[] sort(String[] string) {
        /*Local variables*/
        Map<String, Integer> map=new LinkedHashMap<String, Integer>();
        Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
        int [] lengthsArray=new int[string.length];
        String [] sortedStrings=new String[string.length];
        int counter1=0;
        int counter2=0;

        /* Store all the pairs <key,value>
         * i.e <string[i],string[i].length>
         */
        for(String s:string) {
            System.out.println(s);
            map.put((String) s,  s.length());
            lengthsArray[counter1]= s.length();//store all the lengths
            counter1++;    
        }
        mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
        Arrays.sort(lengthsArray);//sort the array of lengths    

        /*
         * Sort array according to the array of lengths
         * by finding the matching value from the map 
         * then add it to the final string array,and then remove it from the map 
         */
         for(int item:lengthsArray) {    
             for(Map.Entry<String, Integer> e:map.entrySet()) {
                 if(item==e.getValue()) {
                     sortedStrings[counter2]=e.getKey();
                     counter2++;
                     map.remove(e.getKey());
                     break;
                 }   
             }
         }

         map=mapCopy;
         System.out.println(map);//print map
         return sortedStrings;
     }
     public static void main(String[] args) {
         Practise w = new Practise();
         System.out.println(Arrays.toString(w.words));
         w.sort(w.words);           
     }      
}
`

file.txt is:

ACT,CAT,AT,RAT,PAT,TAT

output is:

Here2ACT,CAT,AT,RAT,PAT,TAT


  6

  ACT
  CAT
  AT
  RAT
  PAT
  TAT
  [ACT,CAT,AT,RAT,PAT,TAT, null, null, null, null, null]
  ACT,CAT,AT,RAT,PAT,TAT
  null
  Exception in thread "main" java.lang.NullPointerException
      at Practise.sort(Practise.java:190)
      at Practise.main(Practise.java:239)
Arun Sudhakaran
  • 1,833
  • 2
  • 16
  • 41
abhishek ranjan
  • 532
  • 4
  • 15
  • @Obicere my input file named as file.txt only contains one line which is the same as the `ACT,CAT,AT,RAT,PAT,TAT` , and nothing else.What i wanted to do was to just arrange these words in descending order, that's it. – abhishek ranjan May 05 '18 at 16:15
  • @Obicere did I delete your comment somehow? I can't see your comment which I was a few moments ago – abhishek ranjan May 05 '18 at 16:17
  • Yeah, I just realized you had included it. `scanner.next()` splits by white space, switch this to a comma. I'd also avoid using both a buffered reader and a scanner. [How do I use a delimiter in Java Scanner?](https://stackoverflow.com/questions/28766377/how-do-i-use-a-delimiter-in-java-scanner) – Obicere May 05 '18 at 16:17
  • oh okay. Another point to learn for me, thank you for the link too. – abhishek ranjan May 05 '18 at 16:22
  • I wrote up a quick example here: https://ideone.com/ceclJL – Obicere May 05 '18 at 16:26
  • Yes I was actually reading the link only,and that example really made it simpler only. Thank you for the example, really appreciate it. – abhishek ranjan May 05 '18 at 16:33
  • Please include the minimum amount of code in your question needed to illustrate your problem. http://idownvotedbecau.se/toomuchcode/ –  May 05 '18 at 17:31
  • Sure @LutzHorn, I just wanted to be clear, But I will accept your suggestion gracefully. – abhishek ranjan May 05 '18 at 17:34

1 Answers1

1

null is because of the word array which you have declared ( predefined size ). Probably you can change that and use ArrayList (as it can be of dynamic size) instead of an String array, which can help you resolve. Just to help you, follow below changes:

  1. private List<String> words = new ArrayList<>();
  2. /*update below line in readFile() instead of words[count] = scanLine.next();*/ words.add(scanLine.next());
  3. Change method signature sort(List<String> string)
  4. //also update below declarations int[] lengthsArray = new int[string.size()]; String[] sortedStrings = new String[string.size()];
  5. change Arrays.toString(w.words) to just w.words in print statement

Hope this helps. Everything looks good.

Naveen
  • 800
  • 6
  • 19
  • Thank you, for the detailed information @Naveen, I would say it works partially because my sort function is still not sorting the words by length for some reason. But Thank you for your answer as it solves the issue with Null pointer exception. – abhishek ranjan May 05 '18 at 17:28
  • Great to know that helped you. And for sorting looks like, you have to update your code logic for that... – Naveen May 05 '18 at 17:36