Hi I wrote a java code to find longest word made of other words. My logic is to read the list of words from the text file and add each word into an array (In the text the words are sorted and there will be only one word in each line) After that we check if each element in the array has other elemnts as substrings. If so we count the number of substrings. The element with maximum number of substrings will be the result
The code is running when I give a text file wih only two words. But when there are more than two words I am getting following error
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
I feel the error is occuring in this line if(s.charAt(i1)==w.charAt(j1))
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class Parser
{
public static void main (String[] args) throws IOException
{
String [] addyArray = null;
FileReader inFile = new FileReader ("sample.txt");
BufferedReader in = new BufferedReader (inFile);
String line = "";
int a = 0;
int size=0;
String smallestelement = "";
while(in.ready())
{
line=in.readLine();
while (line != null && line != "\n")
{
size++;
System.out.println(size);
line = in.readLine();
if (line == null) line = "\n";
}
}
addyArray = new String[size];
FileReader inFile2 = new FileReader ("sample.txt");
BufferedReader in2 = new BufferedReader (inFile2);
String line2 = "";
while(in2.ready())
{
line2 = in2.readLine();
while (line2 != null && line2 != "\n")
{
addyArray[a] = line2;
System.out.println("Array"+addyArray[a]);
line2 = in.readLine();
a++;
if (line2 == null) line2 = "\n";
}
}
int numberofsubstrings=0;
int[] substringarray= new int[size];
int count=0,no=0;
for(int i=0;i<size;i++)
{
System.out.println("sentence "+addyArray[i]);
for(int j=0;j<size;j++)
{
System.out.println("word "+addyArray[j]);
String w,s;
s=addyArray[i].trim();
w=addyArray[j].trim();
try{
for(int i1=0;i1<s.length();i1++)
{
if(s.equals(w)&& s.indexOf(addyArray[j-1].trim()) == -1)
{}
else
{
if(s.charAt(i1)==w.charAt(0))
{
for(int j1=0;j1<w.length();j1++,i1++)
{
if(s.charAt(i1)==w.charAt(j1)) //I feel the error is occuring here
{ count=count+1;}
if(count==w.length())
{no=no+1;count=0;};
}
}
}
}
System.out.println(no);
}
catch(Exception e){System.out.println(e);}
substringarray[i]=no;
no=0;
}
}
for(int i=0;i<size;i++)
{
System.out.println("Substring array"+substringarray[i]);
}
Arrays.sort(substringarray);
int max=substringarray[0];
System.out.println("Final result is"+addyArray[max]+size);
}
}
This is the problem:
for(int j1=0;j1<w.length();j1++,i1++)
On each iteration through the loop, you're incrementing i1 as well as j1. i1 could already be at the end of s, so after you've incremented it, s.charAt(i1) is going to be invalid.
Two asides:
You should look at String.regionMatches
Using consistent indentation and sensible whitespace can make your code much easier to read.
A few tips:
First, always include the full stack trace when you are asking for debugging help. It should point to the exact line number the issue is happening on.
Second, your issue is likely in your most inner loop for(int j1=0;j1<w.length();j1++,i1++) you are incrementing i1 in addition to j1 this will cause i1 to eventually go beyond the size of String s
Finally, you should consider using the String.contains() method for Strings or even a Regular Expression.
When you use string.charAt(x), you must check that it is not beyond string length.
Documentation shows that you will get "IndexOutOfBoundsException if the index argument is negative or not less than the length of this string". And in your particular case, you are only validating in the loop that you are under w length, so it will fail.
As SO already said, the loop runs only taking into account w length, so in case you have a shorter s, it will raise that exception. Check the condition so it goes up to the shorter string or rethink the process.
Related
I have 3 files, "MyFile" , "myOtherFile" , "yetAnotherFile" that my code will be drawing words from to put them in an array, check to see if they start with an uppercase, and if they do, it will also sort them alphabetically.
all 3 have 3 or more words, one has only one word that starts with a lowercase so I can test that invalid input print line
I am somehow getting all 3 to print the invalid line
Added a counter so if counter > 0 it then does the print statement
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class StringSorter {
private String inputFileName;
//private String line;
public StringSorter(String fileName) {
inputFileName = fileName;
}
public void sortStrings() throws IOException {
FileReader input = new FileReader(inputFileName);
BufferedReader myReader = new BufferedReader(input);
String line, data = "";
String[] words;
int posCount = 0;
while ((line = myReader.readLine()) != null)
data += line;
words = data.split(",");
for(int posi = 0; posi < words.length; posi++) {
if(!Character.isUpperCase(words[posi].charAt(0))) {
posCount++;
}
}
if(posCount > 0) {
System.out.print("Invalid input. Word found which does not start with an uppercase letter.");
}
else {
for (int k = 0; k < words.length; k++) {
for (int i = k - 1; i >= 0; i--) {
if (words[i].charAt(0) < words[k].charAt(0)) {
String temp = words[k];
words[k] = words[i];
words[i] = temp;
k = i;
}
}
}
for(int print = 0; print < words.length - 1; print++){
System.out.print(words[print].trim() + ", ");
}
System.out.print(words[words.length-1]);
}
input.close();
myReader.close();
}
}
import java.io.*;
public class TestStringSorter {
public static void main(String[] args) throws IOException {
StringSorter sorterA = new StringSorter("MyFile.txt");
sorterA.sortStrings();
StringSorter sorterB = new StringSorter("myOtherFile.txt");
sorterB.sortStrings();
StringSorter sorterC = new StringSorter("yetAnotherFile.txt");
sorterC.sortStrings();
}
}
Invalid input. Word found which does not start with an uppercase letter.
Invalid input. Word found which does not start with an uppercase letter.
Invalid input. Word found which does not start with an uppercase letter.
I see what might be the problem. You're splitting on ',', but you have spaces after the comma. So you're going to have a "word" like " Dog", and if you test the first character of that, you're going to get a failure, because a space is not an uppercase letter.
Try splitting on:
words = data.split("[,\\s]+");
that would fix the problem with the spaces in the data.
I see another problem that will cause you to probably not get the results you expect. You're concatenating multiple lines together, but not putting anything between the lines, so the last word on one line is going to combine with the first word on the next. You probably want to put a "," between each line when you concatenate them together.
I guess you want to write your own sort. I'll leave that to you or others to debug. But you could just:
Arrays.sort(words)
Maybe you are putting a space before each word and this is what you are trying to check if it is upper-case...
Im writing a program to read in a file and store the strings in arraylist and ints in an array. The file contains strings and ints in the format: String int
I have already got the string section to work, I'm looking to know why the following code is populating my array with the number 7, six times rather than the correct numbers.
Correct output would be:
12, 14, 16, 31, 42, 7
But it gives:
7, 7, 7, 7, 7, 7
Code:
BufferedReader buffy = new BufferedReader(new FileReader(fileName));
while((str = buffy.readLine()) != null) {
for(int i = 0; i <= arrayInt.length - 1; i++) {
for(int k = 0; k <= str.length()-1; k++) {
if(str.substring(k, k + 1).equals(" ")) {
String nums = str.substring(k+1);
arrayInt[i] = Integer.parseInt(nums);
}
}
}
}
buffy.close();
This happens because for each line in file you fill whole array.
Try this:
int i = 0;
BufferedReader buffy = new BufferedReader(new FileReader(fileName));
while((str = buffy.readLine()) != null) {
if(i < arrayInt.length) {
for(int k = 0; k <= str.length()-1; k++) {
if(str.substring(k, k + 1).equals(" ")) {
String nums = str.substring(k+1);
arrayInt[i] = Integer.parseInt(nums);
break;
}
}
i++;
}
}
buffy.close();
Also you can use indexOf
int i = 0;
BufferedReader buffy = new BufferedReader(new FileReader(fileName));
while((str = buffy.readLine()) != null) {
if(i < arrayInt.length) {
int k = str.indexOf(" ");
if(k!=-1) {
String nums = str.substring(k+1);
arrayInt[i] = Integer.parseInt(nums);
}
i++;
}
}
buffy.close();
File read are typically batch/ETL kind of job and if this code is going to production and would be used multiple times instead of only once then I would like to stress on Performance and Ease of Maintenance:
Only read least characters to identify the space index
#talex added a very good line of code i.e. break; inside the loop that way you won't need to read till the end of line but this would only work if the string has no spaces. If the string can contain spaces than you would need lastIndexOf space (" ") or no break; at all.
I prefer using framework method lastIndexOf assuming you are using java because:
it would start reading from right instead of left and assuming the numbers would be always less length than the string it would find index of space faster in most of the cases than reading from start.
2nd benefit is that there are lots of scenarios framework/utilities method already handled so why to reinvent the wheel
int k = str.lastIndexOf(" ");
last but not the least if someone else is going to maintain this code it would be easier for him/her as there would be enough documentation available.
Only read required lines from files
Seems like you only need certain number of lines to read arrayInt.length if that's the case then you should 'break;' the while loop once the counter i is more than array length.
I/O operations are costly and though you will get right output you would end-up scanning whole file even if it's not required.
Dont forget try-catch-finally
The code assumes that there will not be any issue and it would be able to close the file after done but there could be n number of combinations that can result in error resulting the application to crash and locking the file.
See the below example:
private Integer[] readNumbers(String fileName) throws Exception {
Integer[] arrayInt = new Integer[7];
String str = null;
BufferedReader buffy = new BufferedReader(new FileReader(fileName));
try {
int i=0;
while ((str = buffy.readLine()) != null) {
if(i> arrayInt.length){
break;
}
//get last index of " "
int k = str.lastIndexOf(" ");
if(k > -1){
String nums = str.substring(k+1);
arrayInt[i] = Integer.parseInt(nums);
}
//increment the line counter
i++;
}
} catch (Exception ex) {
//handle exception
} finally {
buffy.close();
}
return arrayInt;
}
The code below has several functions which allow for things such as writing data to a document, reading it and putting the data in an array for a JTable later down the line.
package tabletest.populatetable;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class GetData {
DataClass[] data = new DataClass[500];
int nextPosition = 0;
public GetData() {
readData();
}
public void writeData()
{
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("resources/tabledata.txt")));
for(int i=0; i < nextPosition; i++) {
bw.write(data[i].toString());
bw.newLine();
}
bw.close();
} catch(Exception e) {
System.out.println("Invalid Data input");
}
}
public void readData()
{
try {
BufferedReader br = new BufferedReader(new FileReader(new File("resources/tabledata.txt")));
String nextData = br.readLine();
String[] arrayStringData;
while (nextData != null) {
try {
arrayStringData = nextData.split(",");
} catch(NullPointerException nPE) {
arrayStringData = new String[] {" ", " "};
}
for(int i = 0; i < arrayStringData.length - 1; i++) {
if(arrayStringData[i] == null || arrayStringData[i] == "") {
arrayStringData[i] = " ";
}
}
DataClass getData = new DataClass();
getData.col1 = arrayStringData[0].trim();
getData.col2 = arrayStringData[1].trim();
data[nextPosition] = getData;
nextPosition++;
nextData = br.readLine();
}
br.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public String[][] dataInTableForm() {
final int colCount = 2;
String[][] temp = new String[nextPosition][colCount];
for(int i = 0; i < nextPosition; i++) {
temp[i][0] = data[i].col1;
temp[i][1] = data[i].col2;
}
return temp;
}
private class DataClass {
String col1;
String col2;
public String toString() {
return col1 + ", " + col2;
}
}
}
The document which it is reading, resources/tabledata.txt, is 12 lines long and it looks like this.
asfias, adsnj
aw,aerfae
aw,aewaa
,tre
asfd,
okfas,af
e,ds
sw,f
,
asfias, adsnj
aw,aerfae
aw,aewaa
The problem is on line 9 of the text document. This is where it is just a , on its own. When there is something before or after the comma this seems to work fine and I checked by removing the line to see if it definitely was the comma causing the problem.
When I looked at the console I discovered the problem was a ArrayIndexOutOfBoundsException and the stack trace is below.
java.lang.ArrayIndexOutOfBoundsException: 0
at tabletest.populatetable.GetData.readData(GetData.java:55)
at tabletest.populatetable.GetData.<init>(GetData.java:14)
at tabletest.Table.createTablePanel(Table.java:76)
at tabletest.Table.createPanels(Table.java:34)
at tabletest.Table.runGUI(Table.java:24)
at tabletest.Table.main(Table.java:150)
Line 55 of the code is getData.col1 = arrayStringData[0].trim();
As you can see in the code I attempted several things to prevent this occurring but I have had no luck. I also tried removing the .trim() from the end of the line; however, exactly the same problem occurs.
I would appreciate any help in fixing this problem.
Javadoc of split(String regex) says:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
So, ",".split(",") will return an empty array, i.e. new String[0].
If you want to keep trailing empty strings, use ",".split(",", -1), which will return new String[] { "", "" }.
The split function will cut out the "," delimiter and return an empty array.
Your try-catch block is catching a null pointer exception if the nextData array is null, not if the output array is empty.
The for loop would only work if the output array contains null strings (which it doesn't).
String.split yanks the delimiter out of the resulting array. So, for a string with just "," your array would be of length 0 (the element at index 0 does not exist).
What you need to do is check whether the length is greater than 0. You can do this using the code arrayStringData.length > 0 in an if statement before trying to access arrayStringData
okay basically im wanting to separate the elements in a string from int and char values while remaining in the array, but to be honest that last parts not a requirement, if i need to separate the values into two different arrays then so be it, id just like to keep them together for neatness. this is my input:
5,4,A
6,3,A
8,7,B
7,6,B
5,2,A
9,7,B
now the code i have so far does generally what i want it to do, but not completely
here is the output i have managed to produce with my code but here is where im stuck
54A
63A
87B
76B
52A
97B
here is where the fun part is, i need to take the numbers and the character values and separate them so i can use them in a comparison/math formula.
basically i need this
int 5, 4;
char 'A';
but of course stored in the array that they are in.
Here is the code i have come up with so far.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class dataminingp1
{
String[] data = new String[100];
String line;
public void readf() throws IOException
{
FileReader fr = new FileReader("C:\\input.txt");
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null)
{
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
System.out.println("Data length: "+data.length);
String[][] root;
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
root = new String[lines.size()][];
lines.removeAll(Arrays.asList("", null)); // <- remove empty lines
for(int a =0; a<lines.size(); a++)
{
root[a] = lines.get(a).split(" ");
}
String changedlines;
for(int c = 0; c < lines.size(); c++)
{
changedlines = lines.get(c).replace(',', ' '); // remove all commas
lines.set(c, changedlines);// Set the 0th index in the lines with the changedLine
changedlines = lines.get(c).replaceAll(" ", ""); // remove all white/null spaces
lines.set(c, changedlines);
changedlines = lines.get(c).trim(); // remove all null spaces before and after the strings
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
}
public static void main(String[] args) throws IOException
{
dataminingp1 sarray = new dataminingp1();
sarray.readf();
}
}
i would like to do this as easily as possible because im not to incredibly far along with java but i am learning so if need be i can manage with a difficult process. Thank you in advance for any at all help you may give. Really starting to love java as a language thanks to its simplicity.
This is an addition to my question to clear up any confusion.
what i want to do is take the values stored in the string array that i have in the code/ input.txt and parse those into different data types, like char for character and int for integer. but im not sure how to do that currently so what im asking is, is there a way to parse these values all at the same time with out having to split them into different arrays cause im not sure how id do that since it would be crazy to go through the input file and find exactly where every char starts and every int starts, i hope this cleared things up a bit.
Here is something you could do:
int i = 0;
for (i=0; i<list.get(0).size(); i++) {
try {
Integer.parseInt(list.get(0).substring(i, i+1));
// This is a number
numbers.add(list.get(0).substring(i, i+1));
} catch (NumberFormatException e) {
// This is not a number
letters.add(list.get(0).substring(i, i+1));
}
}
When the character is not a number, it will throw a NumberFormatException, so, you know it is a letter.
for(int c = 0; c < lines.size(); c++){
String[] chars = lines.get(c).split(",");
String changedLines = "int "+ chars[0] + ", " + chars[1] + ";\nchar '" + chars[0] + "';";
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
It is very easy, if your input format is standartized like this. As long as you dont specify more (like can have more than 3 variables in one row, or char can be in any column, not only just third, the easiest approach is this :
String line = "5,4,A";
String[] array = line.split(",");
int a = Integer.valueOf(array[0]);
int b = Integer.valueOf(array[1]);
char c = array[2].charAt(0);
Maybe something like this will help?
List<Integer> getIntsFromArray(String[] tokens) {
List<Integer> ints = new ArrayList<Integer>();
for (String token : tokens) {
try {
ints.add(Integer.parseInt(token));
} catch (NumberFormatException nfe) {
// ...
}
}
return ints;
}
This will only grab the integers, but maybe you could hack it around a bit to do what you want :p
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
String[][] root = new String[lines.size()][];
for (int a = 0; a < lines.size(); a++) {
root[a] = lines.get(a).split(","); // Just changed the split condition to split on comma
}
Your root array now has all the data in the 2d array format where each row represents the each record/line from the input and each column has the data required(look below).
5 4 A
6 3 A
8 7 B
7 6 B
5 2 A
9 7 B
You can now traverse the array where you know that first 2 columns of each row are the numbers you need and the last column is the character.
Try this way by using getNumericValue() and isDigit methods. This might also work,
String myStr = "54A";
boolean checkVal;
List<Integer> myInt = new ArrayList<Integer>();
List<Character> myChar = new ArrayList<Character>();
for (int i = 0; i < myStr.length(); i++) {
char c = myStr.charAt(i);
checkVal = Character.isDigit(c);
if(checkVal == true){
myInt.add(Character.getNumericValue(c));
}else{
myChar.add(c);
}
}
System.out.println(myInt);
System.out.println(myChar);
Also check, checking character properties
I'm having a problem counting the number of words in a file. The approach that I am taking is when I see a space or a newLine then I know to count a word.
The problem is that if I have multiple lines between paragraphs then I ended up counting them as words also. If you look at the readFile() method you can see what I am doing.
Could you help me out and guide me in the right direction on how to fix this?
Example input file (including a blank line):
word word word
word word
word word word
You can use a Scanner with a FileInputStream instead of BufferedReader with a FileReader. For example:-
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
I would change your approach a bit. First, I would use a BufferedReader to read the file file in line-by-line using readLine(). Then split each line on whitespace using String.split("\\s") and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).
This is just a thought. There is one very easy way to do it. If you just need number of words and not actual words then just use Apache WordUtils
import org.apache.commons.lang.WordUtils;
public class CountWord {
public static void main(String[] args) {
String str = "Just keep a boolean flag around that lets you know if the previous character was whitespace or not pseudocode follows";
String initials = WordUtils.initials(str);
System.out.println(initials);
//so number of words in your file will be
System.out.println(initials.length());
}
}
Just keep a boolean flag around that lets you know if the previous character was whitespace or not (pseudocode follows):
boolean prevWhitespace = false;
int wordCount = 0;
while (char ch = getNextChar(input)) {
if (isWhitespace(ch)) {
if (!prevWhitespace) {
prevWhitespace = true;
wordCount++;
}
} else {
prevWhitespace = false;
}
}
I think a correct approach would be by means of Regex:
String fileContent = <text from file>;
String[] words = Pattern.compile("\\s+").split(fileContent);
System.out.println("File has " + words.length + " words");
Hope it helps. The "\s+" meaning is in Pattern javadoc
import java.io.BufferedReader;
import java.io.FileReader;
public class CountWords {
public static void main (String args[]) throws Exception {
System.out.println ("Counting Words");
FileReader fr = new FileReader ("c:\\Customer1.txt");
BufferedReader br = new BufferedReader (fr);
String line = br.readLin ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println(count);
}
}
Hack solution
You can read the text file into a String var. Then split the String into an array using a single whitespace as the delimiter StringVar.Split(" ").
The Array count would equal the number of "Words" in the file.
Of course this wouldnt give you a count of line numbers.
3 steps: Consume all the white spaces, check if is a line, consume all the nonwhitespace.3
while(true){
c = inFile.read();
// consume whitespaces
while(isspace(c)){ inFile.read() }
if (c == '\n'){ numberLines++; continue; }
while (!isspace(c)){
numberChars++;
c = inFile.read();
}
numberWords++;
}
File Word-Count
If in between words having some symbols then you can split and count the number of Words.
Scanner sc = new Scanner(new FileInputStream(new File("Input.txt")));
int count = 0;
while (sc.hasNext()) {
String[] s = sc.next().split("d*[.#:=#-]");
for (int i = 0; i < s.length; i++) {
if (!s[i].isEmpty()){
System.out.println(s[i]);
count++;
}
}
}
System.out.println("Word-Count : "+count);
Take a look at my solution here, it should work. The idea is to remove all the unwanted symbols from the words, then separate those words and store them in some other variable, i was using ArrayList. By adjusting the "excludedSymbols" variable you can add more symbols which you would like to be excluded from the words.
public static void countWords () {
String textFileLocation ="c:\\yourFileLocation";
String readWords ="";
ArrayList<String> extractOnlyWordsFromTextFile = new ArrayList<>();
// excludedSymbols can be extended to whatever you want to exclude from the file
String[] excludedSymbols = {" ", "," , "." , "/" , ":" , ";" , "<" , ">", "\n"};
String readByteCharByChar = "";
boolean testIfWord = false;
try {
InputStream inputStream = new FileInputStream(textFileLocation);
byte byte1 = (byte) inputStream.read();
while (byte1 != -1) {
readByteCharByChar +=String.valueOf((char)byte1);
for(int i=0;i<excludedSymbols.length;i++) {
if(readByteCharByChar.equals(excludedSymbols[i])) {
if(!readWords.equals("")) {
extractOnlyWordsFromTextFile.add(readWords);
}
readWords ="";
testIfWord = true;
break;
}
}
if(!testIfWord) {
readWords+=(char)byte1;
}
readByteCharByChar = "";
testIfWord = false;
byte1 = (byte)inputStream.read();
if(byte1 == -1 && !readWords.equals("")) {
extractOnlyWordsFromTextFile.add(readWords);
}
}
inputStream.close();
System.out.println(extractOnlyWordsFromTextFile);
System.out.println("The number of words in the choosen text file are: " + extractOnlyWordsFromTextFile.size());
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
This can be done in a very way using Java 8:
Files.lines(Paths.get(file))
.flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
.filter(s->s.length()>0).count();
BufferedReader bf= new BufferedReader(new FileReader("G://Sample.txt"));
String line=bf.readLine();
while(line!=null)
{
String[] words=line.split(" ");
System.out.println("this line contains " +words.length+ " words");
line=bf.readLine();
}
The below code supports in Java 8
//Read file into String
String fileContent=new String(Files.readAlBytes(Paths.get("MyFile.txt")),StandardCharacters.UFT_8);
//Keeping these into list of strings by splitting with a delimiter
List<String> words = Arrays.asList(contents.split("\\PL+"));
int count=0;
for(String x: words){
if(x.length()>1) count++;
}
sop(x);
So easy we can get the String from files by method: getText();
public class Main {
static int countOfWords(String str) {
if (str.equals("") || str == null) {
return 0;
}else{
int numberWords = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
numberWords++;
}
}
return ++numberWordss;
}
}
}