OK i have been stuck with this particular problem and driving me crazy any insight would be helpful. I am trying to create a program that asks user for a string and using the scanner method count the instances it appears in a txt file below is the code oh the professor didnt want bufferread just plain scanner.

package scanner;

import java.io.*;
import java.util.Scanner;

public class Main {


    public static void main(String[] args) throws IOException

    {

        // this is for the user to input string
        Scanner keyboard = new Scanner(System.in);
        System.out.print("what do you want to search for: ");
        String input = keyboard.nextLine();


        //this is path of file
       Scanner mob = new Scanner
       ("C:\\Users\\Eduardo    Dennis\\Documents\\cdi.txt");

         int counter = 0;

    // this is supposed to go through every word and if the input 
        matches any string in the path to counter and repeat loop untill
        end of file at which it prints counter how many instances of the
         word it found, in theory all is well but it does not do it !
 while (mob.hasNext())
       {
          if  (mob.equals(input));
           counter++;
         }

System.out.println(counter);

    }

}

I would be greatful if someone would help me thanks in advance

And what, exactly, is the problem? You might want to try using trim on the first nextLine call to remove extraneous whitespace (to include any possible newline, but I believe the nextLine call strips that, check the API docs about that though, as I am, currently, too lazy to do it for you).

Hmm, I thought the genius bar was set a little higher.

Read carefully the API doc on hasNext(), especially the part about not advancing. Once you actually get the token, you want to compare that with "input", not the scanner "mob".

Also, for future reference, don't create multiple threads for your question. One will suffice.

This is what i have now

package scanner;

import java.io.*;
import java.util.Scanner;

public class Main {

    
    public static void main(String[] args) throws IOException

    {

        
        
        

        Scanner keyboard = new Scanner(System.in);
       System.out.print("what do you want to search for: ");
       String input = keyboard.nextLine();

      

       Scanner mob = new Scanner
    (new File("C:\\Users\\Eduardo Dennis\\Documents\\cdi.txt"));
      
 int counter = 0;

 while (mob.hasNext())
       {
    
       if (mob.nextLine().equals(input));
       counter++;

      
       }
 
 System.out.println(counter);


    }

}

its giving me an off the wall number 5

I don't think you want that semi-colon on the end of your if() statement - it makes for an empty statement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.