File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+
4
+ /**
5
+ * @author Kyler Smith, 2017
6
+ *
7
+ * Implementation of a character count.
8
+ * (Slow, could be improved upon, effectively O(n).
9
+ * */
10
+
11
+ public class CountChar {
12
+
13
+ public static void main (String [] args ) {
14
+ Scanner input = new Scanner (System .in );
15
+ System .out .print ("Enter your text: " );
16
+ String str = input .nextLine ();
17
+
18
+ System .out .println ("There are " + CountCharacters (str ) + " characters." );
19
+ }
20
+
21
+
22
+
23
+ /**
24
+ * @param str: String to count the characters
25
+ *
26
+ * @return int: Number of characters in the passed string
27
+ * */
28
+
29
+ public static int CountCharacters (String str ) {
30
+
31
+ int count = 0 ;
32
+
33
+ if (str .isEmpty () || str == null )
34
+ return -1 ;
35
+
36
+ for (int i = 0 ; i < str .length (); i ++)
37
+ if (!Character .isWhitespace (str .charAt (i )))
38
+ count ++;
39
+
40
+ return count ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments