-1

** I want to get text from the user and find the number of words in the text according to the word searched. BufferedReader sets the readLine method to get all rows with while, but the program gives a null pointer exception error .

The program worked fine when I used a single readline.

I think the problem is in the while loop but I do not understand the problem.**


Please Write Path : C:\Users\Soul Collector\Desktop\yazi okuma

Please Write the Name of Text : buffer

Text File :

hi hello my name is suat

hello there

Hello

Write the key word : hi

Exception in thread "main" java.lang.NullPointerException

at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)

C:\Users\Soul Collector\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

BUILD FAILED (total time: 18 seconds)


        if(press == 2 )
           {

        System.out.print("Please Write Path : ");
        scan.nextLine();
        path = scan.nextLine();

        System.out.print("Please Write the Name of Text : ");
        txtname = "\\"+ scan.nextLine() + ".txt";

        finalpath = path + txtname;

        File dosya = new File(finalpath);
        FileReader fr = new FileReader(dosya);
        BufferedReader br = new BufferedReader(fr);
        String dizi;
        while((dizi = br.readLine()) != null){
            System.out.println(dizi);

        }
           br.close();



       /* StringTokenizer st = new StringTokenizer(dizi);

        while(st.hasMoreTokens()){
        System.out.println(st.nextToken());



    }*/ 

        String search=null;
        System.out.println("Write the key word : ");
       search = scan.nextLine();

        Scanner s = new Scanner(dizi.toLowerCase());
        while (s.hasNext()) {
       toplamkelime++;
           if (s.next().equals(search))
               kelime ++;
                  }
        System.out.println("Key Word : " + search);
        System.out.println("Count of key word : " + kelime);
        System.out.println("\n\n\n Total Count of Words : " + toplamkelime );



    }
Suat Alkan
  • 39
  • 6

1 Answers1

0

You are assigning value to 'dizi' within while conditions, so it was overwritten everytime. When there is something to read, 'dizi' has a value and get printed inside the while loop.

When nothing else to read 'dizi' is then has null value. So when you call 'dizi.toLowerCase()' later down the line, you get null pointer exception.

To fix the issue you need to keep track of all read dizi by using List or append them to another String.

DJ.
  • 6,664
  • 1
  • 33
  • 48