Alex Mccane
Alex Mccane

Reputation: 53

Counting words in a string in JAVA

Trying to write a program that will count the words in a string using simple string methods and ran into a "cannot find symbol" error. I know this is because of the "count" variable but I cant think of any other way to do this. Any help appreciated. By the way the logic i'm using is counting the spaces and then adding 1.

import java.util.Scanner;
public class exam{
   public static void main(String[]args)
   {

      Scanner scan = new Scanner(System.in);
      System.out.println("Enter");
      String s1= new String(scan.nextLine());

      for(int num1 =0; num1<= s1.length()-1; num1++)
      {

         if(s1.charAt(num1)==' ')
         {
            int count =0;
            count++;
         }

         System.out.println(count+1);
      }
   }
}

Upvotes: 1

Views: 1270

Answers (2)

acontell
acontell

Reputation: 6932

If you're using Java 8, you can try lambdas and functional programming. For instance, one way of counting the number of spaces of your string and adding one using lambdas could be:

import java.util.Scanner;

public class stream {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter");
        String s1= new String(scan.nextLine());
        System.out.println(s1.chars().reduce(1, (a, b) -> a + (b == ' ' ? 1 : 0)));
    }
}

Hope it helps.

Upvotes: 0

janos
janos

Reputation: 124844

Declare the count variable outside of the if condition. Instead of this:

if(s1.charAt(num1)==' ')
{
int count =0;
count++;
}

Like this:

int count =0;
if(s1.charAt(num1)==' ')
{
count++;
}

That will solve the "cannot find symbol" error, but your program will still be broken.

To fix, move the declaration outside the for loop.

Btw the program is terribly formatted. Use an IDE like IntelliJ or Eclipse to reformat it nicely.

Upvotes: 1

Related Questions