Variable Scope - JAVA Class/Method - java

I am reading in data from a text file into an ArrayList and then trying to search for a particular string in that ArrayList (the second method).
I believe that I am correctly reading in the data however am struggling to write methods to implement on the ArrayList once it has been filled. For instance, in the checking method below, it is returning a false when I am certain the input String is in the data structure.
I recognize this is likely a problem with my variable scope or how my methods are interacting with each other (i.e, the arraylist is not actually filled with the data when I am checking it).
Any help would be much appreciated - thanks
import java.util.*;
import java.io.*;
public class Word {
ArrayList<String> diclist = new ArrayList<String>();
private void readIn() throws FileNotFoundException {
File file = new File("filepath");
Scanner s = new Scanner(file);
s.useDelimiter("\n");
while (s.hasNextLine()) {
diclist.add(s.nextLine());
}
s.close();
}
public boolean checkIn(String z) {//Check if input string z is in diclist
for (int i = 0; i < diclist.size(); i++) {
if (diclist.get(i).equals(z)) {return true;}
}
return false;
}
}

There are no obvious problems in the code you posted so far. After calling readIn, if the file exists, readable and not empty, the list should get populated. I suggest running it through a debugger.
Note that the checkIn method can be vastly simplified to this:
return diclist.contains(z);

Related

How to retrieve array values and assign to String variable in java

I am trying to store the contents from a file into an array String retval[] , copy that array to String[] fed() and pass the array into main. So far, the array stores and copies but the array method returns null in main String []feed; feed=uio.fed();.
UserIO.java
package fileio;
import classes.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class UserIO
{
public String search (String line0)
{
String line;
try
{
FileInputStream ufin = new FileInputStream("E:\\3rd sem\\OOP\\Projects\\New folder (2)\\BOOK LIBRARY\\fileio\\user.txt");
Scanner sc = new Scanner(ufin);
while (sc.hasNextLine())
{
line=sc.nextLine();
if(line.contains(line0))
{
String retval[]= line.split(" ");
feed= new String[retval.length];
for (String s: retval)
{
System.out.println("\t\t\tFrom retval:"+s);
}
for (int n=0;n<retval.length;n++)
{
feed[n]=retval[n];
System.out.println("\tFrom feed:"+feed[n]);
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return line0;
}
public static String [] feed;
public static String[] fed()
{
String [] fd;
fd= new String[feed.length];
for (int n=0;n<feed.length;n++)
{
fd[n]=feed[n];
System.out.println("From fd:"+fd[n]);
}
return fd;
}
}
Down below is the main method
Execute.java
import java.lang.*;
import java.util.*;
import classes.*;
import fileio.*;
public class Execute
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String adminusername = "a";
String adminpassword = "p";
String readerusername = "r";
String readerpassword = "p";
String nreaderusername;
String nreaderpassword;
Library b = new Library();
UserFileReadWriteDemo ufrwd = new UserFileReadWriteDemo();
UserIO uio = new UserIO();
System.out.println("enter id ");
String id = sc.next();
uio.search(id);
try
{
String []feed;
feed=uio.fed();
//uio.fed()=feed.clone;
for(int s=0;s<feed.length;s+=5)
{
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
Reader c00 = new Reader(nid00, name00, age00,uname00,upassword00);
b.insertReader(c00);
System.out.println(" In main"+feed[s]);
}
}
catch (NullPointerException n)
{
n.printStackTrace();
}
}
Your code is a little bit difficult to read and also has a lot of unnecessary repetitions, for example method fed has no role, why not call search and make search return an array with the found elements? You are making search return the line you are searching for which you already know when you gave search that argument in the first place, it is just returning a useless value.
Also it is difficult to understand what search actually does, from what i see it finds the last occurrence of line0 in the file, because it continues to iterate over lines and every time it finds line0 it will create new feed array in UserIO and eliminate all the previous array it found, and will return when all file has been read. If this is your intention then this is not the right way to do it as it is inefficient, because you keep creating arrays that will be discarded. If your intention is the last occurrence of line0 then you can just assign a found line to a String variable and when the iteration finishes just split and return that array as it will be the last occurrence of line0 in the file.
As i see it the only way that fed will return null is if there is no line with line0 in the file because search initializes the array if it finds line0 at least once in the file, this way feed will be an uninitialized array which will be a null pointer.
These lines has no meaning:
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
I think you meant nid00 = feed[0+s] and so on, because the way you wrote the assignment to nid00 and the other variables will be always null which will be useless.
Also when you copy arrays try to use Arrays.copyOf methods or System.arraycopy they save you writing several lines and also they are more efficient, read about them in the documentation.
And the last thing, it is not useful to catch nullpointer exception if you wrote your code, in general you must know what your methods do and if there is a nullpointer exception in something you wrote then there is something wrong in your code, if for example a method you wrote returns null then you must know about the possibility of a null return and handle that possible return, this way it will be easier for you to read your code and use it and also for others who use your code.
The nullpointer you are getting is because you trying to get the length of an uninitialized feed inside fed method, you must be very careful.

Duplicate Book Titles using Exceptions

I was given a file that I have to find the duplicates and put them into a new text file. That is the gist of what I am trying to accomplish. Here are the directions I was given:
Your client owns a bookstore, and you will find attached; a text file called Samsbooks.txt with
titles of all the books in the store. Write and Print all the duplicate titles to a file called
SamsDuplicate.txt.
EXAMPLE OUTPUT:
Duplicate Books
Sam’s Bookstore 2021
Jack and Jill
Peter Pan
My Little Pony
Here is my code:
enter code here
//In this program, I will write and print all the duplicate book titles to a new file called
SamsDuplicate.txt.
import java.io.*;
public class bookstore {
public static void main(String[] args) throws IOException {
//Printwriter object for the output file that is called SamsDuplicate.txt.
PrintWriter duplicates = new PrintWriter("SamsDuplicate.txt");
//Bufferreader object for the input file that is called SamsBookstore.txt.
BufferedReader original = new BufferedReader(new
FileReader("C:\\Users\\patti\\Desktop\\Patricks dcom101class\\CSIT
210\\SamsBookstore.txt.docx"));
String begin = original.readLine();
//This while loop will read each line of the SamsBookstore.txt file.
while(begin != null) {
boolean in_stock = false;
//This Bufferreader object is for the output file SamsDuplicate.txt.
BufferedReader output = new BufferedReader(new FileReader("SamsDuplicate.txt"));
String mid = output.readLine();
//This while loop will read each line of the SamsDuplicate.txt file.
while(mid != null) {
if(begin.equals(mid)) {
in_stock = true;
break;
}
mid = output.readLine();
}
//This if statement is if the boolean is false and will also write line from SamsBookstore
file to SamsDuplicate file.
if(!in_stock) {
duplicates.println(begin);
}
begin = original.readLine();
}
//Closing both files.
original.close();
duplicates.close();
System.out.println("Duplicate Books");
System.out.println("Sam's Bookstore 2021");
System.out.println();
System.out.println();
}
}
I cannot use HashMaps or anything of that nature since I have not learned about it yet. I have tried putting in the last System.out.println line: my printerwriter (duplicates), my bufferreader(output), even the name of the new file I created called SamsDuplicate.txt none of them will display the duplicates. Am I missing something here? Any help would be appreciated thanks!
Can you use Set?
Based on your code, it seems that the Samsbooks.txt has a book name per line, right?
Set has a method add, declared boolean add(E e). It returns true if the element was added and false if it was not because it already exists in the collection.
If you cannot use Set, you can implement similar functionality by storing each book name in an array. You'll need to first check if the current book name is already in the array. If it is not, then resize the array +1 and add the new book name to the end.

How do I use this method? (the method takes a text file and convert it into a string)

I'm currently in a High School level Java course. I've been doing plenty of research here, on Stack Overflow, trying to work through a project i'm currently assigned. The project consists of making modifications to, and searching through, various words pulled from an encyclopedia file. This is what I am having trouble with, the very basic form of this project. I already found the method in which to solve this problem, but i wasn't able to find a good way of implementing it. This is a copy of the code i found here: (the third method down contains the portion i took from this site)
class word
{
public String newString;
EasyReader fileIn = new EasyReader("Encyclopedia.txt");
EasyWriter fileOut = new EasyWriter("writeHere.txt");
String fileName="Encyclopedia.txt";
private String onFile;
public word()
{
onFile="";
}
public word(String s)
{
onFile=s;
}
String file = "Encyclopedia.txt";
private String readFile(String file) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line=null;
StringBuilder stringBuilder = new StringBuilder();
String is=System.getProperty("line.seperator");
while((line=reader.readLine())!=null)
{
stringBuilder.append(line);
stringBuilder.append(is);
}
newString=stringBuilder.toString();
return stringBuilder.toString();
}
}
So, the question: how do i use this method? i know it sounds silly, but how do run this method and then use the data later? It is supposed to take a given text file and return a string, but i'm not even sure how to get the return value after it has processed.
Any help would be greatly appreciated. I made an account here just to ask this question. If i need to post this somewhere else, or if there is a better site to use to find an answer and some more basic help, please let me know. Thanks,
-Ethan
The readFile method seems to be doing multiple things at once. It accepts a file argument which overrides the member variable with the same name. Then it reads the file into a String and sets the newString member variable to the result before returning the same result.
So I would recommend first deciding whether the method should return the data or set the member variable. If multiple methods are going to be using the result, it might be useful to use the member variable, otherwise go the return route. Also, you can probably remove the file member variable since it is ignored by the method.
You can rewrite the method to look like this (I just removed the newString=stringBuilder.toString(); line, and I changed it to static since it can be):
private static String readFile(String file) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line=null;
StringBuilder stringBuilder = new StringBuilder();
String is=System.getProperty("line.seperator");
while((line=reader.readLine())!=null)
{
stringBuilder.append(line);
stringBuilder.append(is);
}
return stringBuilder.toString();
}
And wherever you need to use it call it like this (remember to catch the IOException):
try {
String someString = readFile("filename.txt");
} catch(IOException e) {
// handle error
}
Remember it must be called from inside the same class unless you change private to public.
Also, it might be worth reading and following a standard code style. It can really help by distinguishing between different types of variable for example.
Actual method that read string from file is: "readFile". And in your class, you are not calling that.
private String readFile(String file) throws IOException
You can pass file name as parameter, and It will returns read string.
So, how about modify your word(String s), and add method that will return actual result of read file?
public word(String s)
{
onFile=s;
newString = readfile(onFile);
}
public getNewString(){
return newString;
}
Try this:
String file ="/path/to/file.csv"
word myWord = new word();
o = myWord.getClass().getDeclaredMethod("readFile");
o.setAccessible(true);
Object r = o.invoke(myWord);
//print result

List of class objects

I'm stuck.. I trying to parse a text from file in words, but save it in List of objects. Whether it is possible to do so?
public class Text {
public static List<Words> words = new ArrayList<Words>();
}
public class Words {
private String path;
private String[] inside;
private BufferedReader in;
public Words(String path, String[] inside) {
this.inside = inside;
this.path = path;
}
public String[] splittinIntoWords() throws IOException {
in = new BufferedReader(new FileReader(path));
String s;
while ((s = in.readLine()) != null) {
inside = s.split(" ");
//System.out.println(Arrays.toString(inside));
}
return inside;
}
}
and main class
public class Main {
public static void main(String[] args) throws IOException {
String file_name = "book.doc";
String[] inside = null;
Words w = new Words(file_name, inside);
w.splittinIntoWords();
Text.words.add(w); //after add in list i have a reference.
System.out.println(Text.words.toString());
}
}
i do smthg wrong. I understand how to do this with List of Strings
tell me please, it is possible, to add text splitting into words in List of Words
You’re overwriting the array of words Words.inside with each line you read. You need to add the output of split() to a List every time round the while loop, not just at the end.
I would expect your code to display the words in the last line of your file, but possibly it has a blank last line, in which case you will see nothing.
Also, I assume your "book.doc" is not really a .doc format file—word processor files need special parsing; what you have written will only work on plain text files.
there is several things wrong with your code.
Text.words shouldn't be static. Every instance of text consists of a different collection of words.
When you make a "Collection of Words", then it should be Collection< Word>. Because every item inside the collection is just a single item.
but then again, Collection< Word> is just the same as Collection< String>. So use that.
"path", "in" should not be member variables of "Words". Just use them locally in your method. Especially since you never closed "in".
you're overwriting whatever is in "inside" for each line in your file that you loop over. When you have your "Collection< String> words", then just do words.addAll(inside); in
your loop.
Yes, I know this is not an answer, but I'm trying to point you in the right direction. This might help you more in the long run.

How can I recursively print a File Array?

I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.
import java.io.*;
public class RecursiveDir {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args) throws IOException {
System.out.print("Please enter a directory name: ");
File f = new File(br.readLine());
FileFilter filter = new FileFilter() {
public boolean accept(File f) {
if(f.isDirectory()) {
return true;
}
return false;
}
};
File[] list = f.listFiles(filter);
System.out.println(returnDir(list,list.length));
}
public static File returnDir(File[] file,int counter) {
File f = file[counter];
if(counter == 0) {
return file[0];
}else {
return f = returnDir(file,counter--);
}
}
}
EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.
You are going out of the array bound because you need to pass list.length - 1 to the method.
Even if you did that, though, you would have an infinite recursion, because counter-- will use the value of counter, and then decrement it. So that means you are calling returnDir with the current value of counter. Use either --counter, or counter - 1.
What do expect to happen here? You don't seem to be doing anything with the files as you visit them. There is no need for recursion to loop through the files in the directory, the recursion is needed when you hit a file in the list that is a directory.
You are indeed going out of bounds. You need to change
returnDir(list,list.length);
to
returnDir(list,list.length - 1 );
You seem to be missing your System.out.println() calls. You are looping through the files and not doing anything with them.
Your initial call to returnDir should be
returnDir(list,list.length-1);
Paul

Categories