Search String only prints out searches without characters attached - java

I’m new to java and I am working on a project. I am trying to search a text file for a few 4 character acronyms. It will only show or output when it’s just the 4 characters and nothing else. If there is a space or another character attached to it won’t display it… I have tried to make it show the whole line, but have yet to be successful.
The contents of text file:
APLM
APLM12345
ABC0
ABC0123456
CSQV
CSQVABCDE
ZIAU
ZIAUABCDE
The output in console:
APLM
ABC0
CSQV
ZIAU
My Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class searchPdfText
{
public static void main(String args[]) throws Exception
{
int tokencount;
FileReader fr = new FileReader("TextSearchTest.txt");
BufferedReader br = new BufferedReader(fr);
String s = "";
int linecount = 0;
ArrayList<String> keywordList = new ArrayList<String>(Arrays.asList("APLM", "ABC0", "CSQV", "ZIAU" ));
String line;
while ((s = br.readLine()) != null)
{
String[] lineWordList = s.split(" ");
for (String word : lineWordList)
{
if (keywordList.contains(word))
{
System.out.println(s);
break;
}
}
}
}
}

If you take a look at the documentation for ArrayList.contains you will see that it only returns true if your keyword contains the provided string from your file. As such, your code is correct when it only outputs the exact matches found for those provided strings in keywordList.
Instead, if you want to get matches when a part of the provided string contains a keyword, consider iterating through the input and matching it the other way around:
while ((s = br.readLine()) != null) {
String[] lineWordList = s.split(" ");
for (String word : lineWordList) {
// JAVA 8
keywordList.stream().filter(e -> word.contains(e)).findFirst()
.ifPresent(e -> System.out.println(word));
// JAVA <8
for (String keyword : keywordList) {
if (word.contains(keyword)) {
System.out.println(s);
break;
}
}
}
}
Additionally, you may consider following Oracle's Java Naming Conventions with regards to your class name. Each word in your class name should be capitalized. For example, you class might be better named SearchPdfText.

You just need to change your while code for the output you want:
while ((s = br.readLine()) != null) {
if (s.length() == 4){
System.out.println(s);
}
}
If you want only that 4 specific values just create a method to check it like:
public static boolean hasIt(String text){
String [] list = { "APLM", "ABC0", "CSQV", "ZIAU" };
for ( String s : list ){
if (s.equals(text)){
return true;
}
}
return false;
}
And your while to:
while ((s = br.readLine()) != null) {
if (hasIt(s)){
System.out.println(s);
}
}

Related

I need to be able to compare entries of a file - Java

`import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Dokimi {
private static String line;
public static void main (String[] args) throws IOException
{
int x = 0;
BufferedReader br = new BufferedReader(new FileReader("src/film.txt"));
line = br.readLine();
String[] filmline = new String [1000];
while (line != null) {
line = br.readLine();
filmline[x] = line;
x++;
}
br.close();
for (int i = 0; i<x; i++) // after many tries the last change I made is this. This is the testing class.
{
String [] arr = filmline[i].split(": ");
if ( i == x-1) // I know it isn't the best, maybe not even good but I tried many things and had nothing to lose.
{
for ( String ss : arr) {
String test = ss;
if (test.equals("Dancing With The Dogs "))
{
System.out.println("gotcha!");
}
}
}
}
}
}`So, I have a text file with the attributes of some movies. For example :
"film id : 1 film title : Pirates Of Hawai film category : action , comedy film description : A pirate from Hawai drinks rum and goes on an adventure to find more rum."
(every entry in one line) and each time a user is trying to add a new entry I have to make sure the film isn't already on the file. I tried the slpit method (by using ":" and erasing "film id" etc) and StringTokenizer but it only worked on ONE and specified by me line, and not in a loop so that it could read the whole file.
As per here
Change your line a bit to add a ":":
"film id : 1 : film title : Pirates Of Hawai : film category : action , comedy : film description : A pirate from Hawai drinks rum and goes on an adventure to find more rum."
You can try this approach and compare with yours: (use existsfilm to verify if it already exists before add)
public void showAllFilms(){
ArrayList<String[]> films = getFilms();
for(String[] film : films){
System.out.println("id "+film[0]+"\ntitle "+film[1]);
}
}
public existsFilm(String filmName){
ArrayList<String[]> films = getFilms();
for(String[] film : films){
if(film[1].equals(filmName)){
return true;
}
}
return false;
}
public ArrayList<String[]> getFilms(){
ArrayList<String[]> filmList = new ArrayList();
int lineRead = 0;
try{
File file = new File("yourfile.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(":");
if(data.length > 0){
filmList.add(new String[]{data[1],data[3],data[5],data[7]});
}
lineRead++;
}
}catch(Exception ex){
System.out.println("Error reading line "+lineRead);
ex.printStackTrace(); //very ugly using this (common is logging it)
}
return filmList;
}
Don't use StringTokenizer, it's legacy, and should be supported for maintenance reasons, but not be implemented in new code.
Considering the tokens differ each time, you may want to run over the String and using substring here and there, that is, assuming each line contains the same tokens.
Or, change your input in:
"1*Pirates Of Hawaiaction , comedyA pirate from Hawai drinks rum and
goes on an adventure to find more rum."
This way, all tokens are identical, and you will be able to use the split method.

search a word inside file then stored in array

my problem is i read a file then i search a word "(:types"
i want take the words after "(:types" but the code take a line after "(:types"
this is the problem i need to you to find why my code cant store words after
"(:types" ( my code take "
location vehicle cargo)" i need to take ( "space fuel
location vehicle cargo")
sorry for my English
(:types space fuel
location vehicle cargo)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
public class type2 {
public static void main(String[] args){
String filePath = "C:\\test4.txt";
BufferedReader br;
String line = "";
String read=null;
List<String> temps = new LinkedList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
String[] words = line.split(" ");
for (String word : words) {
if (word.equals("(:types") ) {
while((read = br.readLine()) != null){
temps.add(read);
if (word.equals("(:predicates") );
break;
}
String[] tempsArray = temps.toArray(new String[0]);
String [] type=tempsArray[0].split(" ");
System.out.println(tempsArray[0]);
}
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The reason you aren't getting the words that are on the same line is because you don't parse the rest of the line.
First you get the first line with
while((line = br.readLine()) != null)
And then split that on all the spaces with:
String[] words = line.split(" ");
But once you find the string (:types, all you do is start reading from the file again. You never parse the remaining parts of the array words.
If you want to parse the rest of this array, maybe find the index of the string (:types in your array, then just parse all parts after it.
The problem seem very straightforward.
If I understand you correctly you have a file which contain the lines:
(:types space fuel
location vehicle cargo)
You want to find the line containing "(:types" and then save "space" and "fuel".
In your code your read in a new line of text like this
while((line = br.readLine()) != null)
You check line for whether it contains (:types and if it does you store the words in the next line through the code:
while((read = br.readLine()) != null){
temps.add(read);
This above is your problem. To fix this you should change the above code to the following:
for (String word : words){
if(!word.equals("(:types")){
temps.add(read);
}
}

Read file, replace a word and write to a new file in Java

I am trying to read a text file which I then put into an ArrayList and then go through that ArrayList and replace any occurrences of the word "this" with "**". I then want to put this modified ArrayList back into a new file with the newly edited text.
The applications currently reads the lines into the ArrayList correctly and writing to the new file works. However, replaceWords method doesn't appear to be functioning as expected i.e. this is not being replaced by **. Any help would be greatly appreciated!
package com.assignment2s162305.answers;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Question27 {
private List<String> lines = new ArrayList<String>();
// read original file to an ArrayList
public String[] readOriginalFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
// replace words with ****
public void replaceWords() {
Collections.replaceAll(lines, "this", "****");
System.out.println(lines);
}
// write modified ArrayList to a new file
public void writeToNewFile() throws IOException {
FileWriter writer = new FileWriter("output.txt");
for (String str : lines) {
writer.write(str);
}
writer.close();
}
}
package com.assignment2s162305.answers;
import java.io.IOException;
public class Question27Test {
public static void main(String[] args) {
Question27 question27object = new Question27();
String filename = "Hamlet2.txt";
try {
String[] lines = question27object.readOriginalFile(filename);
System.out.println("______ORIGINAL DOCUMENT______\n");
for (String line : lines) {
System.out.println(line);
}
System.out.println("\n\n");
question27object.replaceWords();
question27object.writeToNewFile();
} catch(IOException e) {
// Print out the exception that occurred
System.out.println("Unable to create "+filename+": "+e.getMessage());
}
}
}
Your replaceWords method has a bug. To fix it, you need to loop through the lines and do the replacement in each line. What you have implemented is to replace all lines which are equal to "this" with ****. So this works OK but is not what you wanted.
This this code. This will fix it.
public void replaceWords() {
ArrayList<String> lns = new ArrayList<String>();
for (String ln : lines){
lns.add(ln.replaceAll("this", "****"));
}
lines.clear();
lines = lns;
System.out.println(lines);
}
You are reading lines of text into your array lines. However, Collections.replaceAll doesn't search inside the string to replace the word "this"; it will just test if the entire line is equal to "this", which it certainly isn't.
Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)).
Example:
List<String> lines = new ArrayList<String>();
lines.add("This");
lines.add("this");
lines.add("THIS");
lines.add("this won't work.");
Collections.replaceAll(lines, "this", "****");
System.out.println(lines);
Output:
[This, ****, THIS, this won't work.]
You can split your lines into words, and attempt Collections.replaceAll on the List of words.
Or, you can use String's replace method, which will match the word within the line:
for (int i = 0; i < lines.size(); i++)
{
lines.set(i, lines.get(i).replace("this", "****"));
}
From replaceAll method javadoc:
Replaces all occurrences of one specified value in a list with
another. More formally, replaces with newVal each element e in list
such that (oldVal==null ? e==null : oldVal.equals(e)). (This method
has no effect on the size of the list.)
It means, that you are trying to replace String instance holding exactly "this" text by String instance holding "****" text instead of replacing text inside String object. Note that String is immutable.
You have to iterate list of Strings and replace text using String#replace or String#replaceAll methods.

ArrayIndexOutOfBounds when trying to split a line from reader

I am trying to write a java program to parse relevant strings from a .txt file with a certain format.
I want to use the contents of the .txt file to initiate data for my classes. A sample file would look like this:
Movies
Lord of the Rings: 180
Fight Club: 120
...
Theaters
A:100
B:50
C:200
...
Shows
1,1,960
1,1,1080
1,1,1200
1,3,1020
1,3,1140
2,2,990
2,2,1210
...
Prices
Adult:10
Child:7
Senior:8
...
End
This is what I have so far (and it is returning an error when trying to read the above file to initialize my class.
public static void inititializeFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while((line = reader.readLine()) != null) {
if(line.equals("Movies")) {
while (!(line.equals("Theaters"))) {
String currentline = line;
String[] parts = currentline.split(":");
String part1 = parts[0];
String part2 = parts[1];
movies.add(new Movie(part1, part2));
}
}
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
reader.close();
}
}
Here is a sample program that will read in the file for you, line by line, and has some scenarios to determine what type of line we are looking at. I was lazy and threw the IOExceptions that might be thrown at me in the code - you should never do this, instead modify the program to use a try catch.
import java.io.*;
public class tmp {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null) {
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
br.close();
}
}

How to find certain words in a text file, then find numbers in Java?

I have the following text file (answers.txt):
Problem A: 23|47|32|20
Problem B: 40|50|30|45
Problem C: 5|8|11|14
Problem D: 20|23|25|30
What I need is something that will read the problem that I tell it(Problem A, Problem B), then read the numbers after it, which are separated by the lines, and print it out like this:
Answers for Problem A: a.23 b.47 c.32 d.20
Does anyone know how this can be done? I've been stuck on it for a while.
Read the lines one by one, split the lines at " " first. The you will get an array with three parts "Problem", "A:" and "23|47|32|20". Then split the third part at "|" so you will get a second array with four parts "23,"47","32","20".
Combine all to get the output you want.
If you want info on how to read lines from a file, or spilt strings then there are billions of tutorials online on how to do that so I wont go into detail on how its done. IM sure you can find them.
Check out this code!
It assumes that you have such file format:
Problem A:
23|7|32|20
Problem B:
40|50|30|45
Problem C:
5|8|11|14
Problem D:
20|23|25|30
because you wrote "numbers after it, which are separated by the lines"
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("answers.txt"));
List<String> dataList = new ArrayList<String>();
while(sc.hasNextLine()){
dataList.add(sc.nextLine());
}
System.out.println(dataList);
Map<String,String> map = new HashMap<String,String>();
for(int i=0;i<dataList.size();i=i+2){
map.put(dataList.get(i),dataList.get(i+1));
}
for(Entry<String,String> en:map.entrySet()){
System.out.println(en.getKey()+" : "+en.getValue());
}
String problemC = map.get("Problem C:");
String splitted[] = problemC.split("\\|");
System.out.println("Get me problem C: "+String.format("a:%s, b:%s, c:%s, d:%s",splitted[0],splitted[1],splitted[2],splitted[3]));
}
}
Hope this helps!
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new FileReader(new File("answers.txt")));
String lineRead = null;
String problem = "Problem A";//Get this from user Input
List<String> numberData = new ArrayList<String>();
while((lineRead = br.readLine())!=null)
{
if(lineRead.contains(problem))
{
StringTokenizer st = new StringTokenizer(lineRead,":");
String problemPart = st.nextToken();
String numbersPart = st.nextToken();
st = new StringTokenizer(lineRead,"|");
while(st.hasMoreTokens())
{
String number = st.nextToken();
System.out.println("Number is: " + number);
numberData.add(number);
}
break;
}
}
System.out.println("Answers for " + problem + " : " + numberData );
}
Read the lines one by one, split the lines with :. The you will get an array with two parts "Problem A:" and "23|47|32|20". Then split the second part at "|" so you will get a second array with four parts "23,"47","32","20".
Combining all this you will get the output you want.
Cheers!
Use java.util.Scanner and you can filter the integers in the file.
Scanner s = new Scanner (new File ("answers.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is integer
System.out.print(s.nextInt());
} else {
s.next(); // else read the next token
}
}
Do you know how to read line by line ? If not , chect it How to read a large text file line by line in java?
To sub your string data there have many ways to do. You can sub as you wish. Here for my code..
String data = yourReader.readLine();
String problem = data.substring("Problem".length(), data.indexOf(":"));
System.err.println("Problem is " + problem);
data = data.substring(data.indexOf(":") + 2, data.length());
String[] temp = data.split("\\|");
for (String result : temp) {
System.out.println(result);
}
Assuming there are always four possible answers as in your Example:
// read complete file in fileAsString
String regex = "^(Problem \\w+): (\\d+)\\|(\\d+)\\|(\\d+)\\|(\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(fileAsString);
//and so on, read all the Problems using matcher.find() and matcher.group(int) to get the parts
// put in a Map maybe?
// output the one you want...
I might suggest creating a simple data type for the purpose of organization:
public class ProblemAnswer {
private final String problem;
private final String[] answers;
public ProblemAnswer(String problem, String[] answers) {
this.problem = problem;
this.answers = new String[answers.length];
for (int i = 0; i < answers.length; i++) {
this.answers[i] = answers[i];
}
}
public String getProblem() {
return this.problem;
}
public String[] getAnswers() {
return this.answers;
}
public String getA() {
return this.answers[0];
}
public String getB() {
return this.answers[1];
}
public String getC() {
return this.answers[2];
}
public String getD() {
return this.answers[3];
}
}
Then the reading from the text file would look something like this:
public void read() {
Scanner s = new Scanner("answers.txt");
ArrayList<String> lines = new ArrayList<String>();
while (s.hasNext()) {
lines.add(s.nextLine());//first separate by line
}
ProblemAnswer[] answerKey = new ProblemAnswer[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String[] divide = lines.get(i).split(": "); //0 is the problem name, 1 is the list
//of answers
String[] answers = divide[1].split("|"); //an array of the answers to a given
//question
answerKey[i] = new ProblemAnswer(divide[0], answers); //add a new ProblemAnswer
//object to the key
}
}
Now that leaves you with an answer key with ProblemAnswer objects which is easily checked
with a simple .equals() comparison on the getProblem() method, and whatever index is matched, you have all the answers neatly arranged right within that same object.

Categories

Resources