I have been trying to write a program that reads a text file and searches for a words that ends with 'ing' using java but I could not done it. Also display words that are accepted "ends with ing" and rejected word "doesnot end with ing".
Asked
Active
Viewed 322 times
1
-
2`I have been trying` can you share your tries ? – azro Mar 21 '21 at 08:54
-
Does this answer your question? [Check if string ends with certain pattern](https://stackoverflow.com/questions/12310978/check-if-string-ends-with-certain-pattern) – Criss Hills Mar 21 '21 at 09:12
1 Answers
1
This link https://stackabuse.com/reading-a-file-line-by-line-in-java/ shows you how to get data from a txt file. I implemented the code that searches for the "accepted" strings and the "rejected" strings as well. The way that the code works is that I use the .substring() method to check the last 3 characters of the string, and if it is 'ing', then I add it to the "accepted" string, and if not, I add it to the "notAccepted" string.
import java.io.File;
import java.util.*;
public class StackOverflowQuestion{
public static void main(String[] args)throws Exception {
Scanner scanner = new Scanner(new File("yourFileName.txt"));
String st = "";
String st2 = "";
String accepted = "";
String notAccepted = "";
while (scanner.hasNextLine()) {
st= scanner.next();
if(st.length() <= 3){
notAccepted += st + " ";
continue;
} else {
st2 = st.substring(st.length() - 3,st.length());
}
if(st2.equals("ing")){
accepted += st + " ";
} else {
notAccepted += st + " ";
}
}
System.out.println("List of accepted strings ie ending with 'ing': " + accepted);
System.out.println("List of rejected strings ie not ending with 'ing': " + notAccepted);
}
}
You need to have the "throws Exception" code just in case the file isn't found. To make sure that you get strings that are equal to or less than 3 characters long, you need to check that before you make the substrings. Hope it helped!

Sergio Hernandez
- 21
- 3
-
this is so useful thanks, but unfortunately it does not read words that is less than 3 letters. when I read a text file which contains a words with less than 3 letters it gives me error. – Diyar Mhamad Mar 21 '21 at 12:40
-