I am trying to write a program Count.java that counts the characters, newlines, and words in a string input by the user with a return value that is an array of the three counts.
I've written a program that is supposed to store a string entered by the user from the main method as the variable text in the method public static int[] analyze(String text)
and, then, analyze it with the three integer count variables wordCount
, charCount
, and lineCount
.
public class Count {
public static void main(String[] args) {
System.out.print("Please enter a string: ");
System.out.println(arr);
System.out.println("Total number of words: " + arr[0]);
System.out.println("Total number of characters: " + arr[1]);
System.out.println("Total number of newlines: " + arr[2]);
}
public static int[] analyze(String text) {
Scanner in = new Scanner(System.in);
String text = in.nextLine();
int wordCount = 0;
int charCount = 0;
int lineCount = 1;
int[] arr;
arr = new arr[] {wordCount, charCount, lineCount};
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' && text.charAt(i + 1) != ' ') {
wordCount++;
}
if (text.charAt(i) != ' ') {
charCount++;
}
}
if (text.charAt(i) == text.charAt(i)) {
lineCount++;
}
return arr;
}
}
I want it to output the number of characters, newlines, and words of the user's input string. However, when I try to run it, the compiler doesn't recognize my string variable text and array arr. Any suggestion for how I might fix this?