0

Question is to find the number of words in a string entered by the user, below code give a correct output when there is only one whitespace between each word but fails when there is more than one whitespace between each word. Can anyone please help me to find out what is wrong with this code.?

CODE -

import java.util.*;         
                                                                                         
public class Main
{
public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the String");
    
    String str1 = sc.nextLine();
    
    String str2 = str1.trim(); 
    
    String strar[] = str2.split(" ");
    
    
    int count = 0;
    
    for(String s:strar)
    {
        
        if (!(s.equals(" ")))
        {
        count++;
        }
    }
    
    System.out.println(count);
    
}}
K D
  • 11
  • 4
  • 3
    Try something like `str2.split(" +");` That's a space followed by a plus sign. The problem is now you're requiring the delimiter to be exactly one space, and I don't think that's what you want. – markspace Mar 01 '22 at 00:43
  • *fails when* --- i don't think the program will throw exception even when multiple spaces delimited. maybe you can add `s=s.trim()` in loop. – Lei Yang Mar 01 '22 at 00:44
  • @LeiYang If the answer is wrong, then it has failed no? – Scary Wombat Mar 01 '22 at 00:45
  • there's no assertion, nor did the OP stated criteria of success or fail. – Lei Yang Mar 01 '22 at 00:46
  • @LeiYang *i don't think the program will throw exception* - The OP never mentions anything about an Exception. Just saying. – Scary Wombat Mar 01 '22 at 00:55

0 Answers0