Java Beginner - Counting number of words in sentence

后端 未结 17 1830
忘了有多久
忘了有多久 2021-01-01 05:29

I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on

17条回答
  •  忘掉有多难
    2021-01-01 06:05

    import java.util.HashMap;

    import java.util.Map;

    import java.util.Scanner;

    public class WordrCount {

    public static void main(final String[] args) {
        System.out.println("Please Enter Your String: ");
        final Map hm = new HashMap();
        final Scanner sc = new Scanner(System.in);
        final String s1 = sc.nextLine();
        final String[] c1 = s1.split(" ");
        for (int i = 0; i < c1.length; i++) {
            if (!hm.containsKey(c1[i])) {
                hm.put(c1[i], (Integer)1);
            }// if
            else {
                hm.put(c1[i], hm.get(c1[i]) +(Integer) 1);
    
            }// else
        }// for
    
        System.out.println("The Total No Of Words: " + hm);
    
    }// main
    

    }// WordCount

提交回复
热议问题