In: Computer Science
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int[] WordsCharsLetters = {0,1,2};
while(input.hasNext())
{
String sentence=input.nextLine();
if(sentence!=null&&sentence.length()>0){
WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0];
WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1];
WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2];
}
else
break;
}
input.close();
System.out.println("Words: " + WordsCharsLetters[0]);
System.out.println("Characters: " + WordsCharsLetters[1]);
System.out.println("Letters: " + WordsCharsLetters[2]);
}
static int[] calculateAndPrintChars(String sentence)
{
int[] WCL = new int[3];
String[] sentenceArray=sentence.split(" ");
WCL[0] = sentenceArray.length;
int letterCount=0;
for(int i=0;i<sentence.length();i++)
{
if(Character.isLetter(sentence.charAt(i)))
letterCount++;
}
WCL[1] = sentence.length();
WCL[2] = letterCount;
return WCL;
}
}
This is my code. It works but not the way I want it to. I need the user to input a sentence and the output to say how many words, letters, and characters there are in the sentence. In order for this code to give an output I've been having to type the sentence, press enter a few times, then a letter and then it gives me my output. Please help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner input = new
Scanner(System.in);
int[] WordsCharsLetters = { 0, 1, 2
};
while (true) {
System.out.println("Enter sentense (q to stop): ");
String sentence
= input.nextLine();
if
(!sentence.equalsIgnoreCase("q")) {
WordsCharsLetters[0] =
calculateAndPrintChars(sentence)[0];
WordsCharsLetters[1] =
calculateAndPrintChars(sentence)[1];
WordsCharsLetters[2] =
calculateAndPrintChars(sentence)[2];
System.out.println("Words: " +
WordsCharsLetters[0]);
System.out.println("Characters: " +
WordsCharsLetters[1]);
System.out.println("Letters: " +
WordsCharsLetters[2]);
} else
break;
}
input.close();
}
static int[] calculateAndPrintChars(String
sentence) {
int[] WCL = new int[3];
String[] sentenceArray =
sentence.split(" ");
WCL[0] =
sentenceArray.length;
int letterCount = 0;
for (int i = 0; i <
sentence.length(); i++) {
if
(Character.isLetter(sentence.charAt(i)))
letterCount++;
}
WCL[1] = sentence.length();
WCL[2] = letterCount;
return WCL;
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME