[Solved] JAVA: I have to write a program to read “sentences” from a file and and then count the number of words and vowels per sentence [closed]


Couple of issues:

  • You are using last user entered sentence while you should use text that you read from file like below:

      StringTokenizer words = new StringTokenizer(text);
      numberofwords=numberofwords+words.countTokens();
    
      for (i=0;i<text.length();i++)
      {
          ch=text.charAt(i);
          if (ch=='a'||ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
          {
              vowels++;
          }
    
      }
      System.out.print(text);
    
  • You keep on reusing the count and hence you get cumulative sum in order to avoid this reset your counters when read every line from file as below:

    vowels = 0;
    numberofwords = 0;

So in all your code should be:

  while((text=sb.readLine())!=null)//counting words
  {
      vowels = 0;
      numberofwords = 0;
      StringTokenizer words = new StringTokenizer(text);
      numberofwords=numberofwords+words.countTokens();

      for (i=0;i<text.length();i++)
      {
          ch=text.charAt(i);
          if (ch=='a'||ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
          {
              vowels++;
          }

      }
      System.out.print(text);
      System.out.print("          "+numberofwords);
      System.out.println("                        "+vowels);

  }    

solved JAVA: I have to write a program to read “sentences” from a file and and then count the number of words and vowels per sentence [closed]