Better way to split my results from reading file? - java

I have a function that reads through a file, and gathers the results into an array list.
The array list looks like this (data)
[12, adam, 1993, 1234, bob, 1992]
I then need to load these details into new objects called patients. This is the current method I have so far for putting each separate array list item into its own patient, yet it keeps bugging me with an error saying I am passing in String String Int, and it needs to be a String.
s looks like this
12, adam, 1993
And this is the code
public void loadPatients()throws Exception
{
ArrayList<String> data = IO_Support.readData("PatientData.txt");
System.out.println(data);
for(String s : data)
{
Sytem.out.println(s);
patientList.add(new Patient(s));
}
}
Is there a way to push my array list result into a string for passing into the patient object, or should I use a different way to split the string results?
Read data looks like this
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}

while (temp != null)
{
temp = in.readLine();
}
First thing, You are never adding your input to the ArrayList.. This while loop makes no sense.. It is just reading user input, and swallowing it on every occassion..
Plus, after seeing your exception, its sure that you are using a 1-arg constructor of Patient class which is not there.. There are only 0-arg constructor and 2-arg constructor in Patient class.. You need to use them indeed.
See this code in loadPatient method.. You need to add a 1-arg constructor in your Patient class to get it compiled..
patientList.add(**new Patient(s)**); --> Will not work
So, in your Patient class, add: -
public Patient(String s) {
this.s = s;
}
this.s is the instance variable to store s that you passed..

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.

How do I access an array within an array?

Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);

Variable Scope - JAVA Class/Method

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);

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.

Categories