Inserting .readLine(); into my array of strings - java

im a new coder here.
My program in a nutshell: Im working on a fantasy football trade calculator using player values to understand what would be a good trade.
My problem: I am able read from my file, count the positions however unable to add my string to my array of playNames. I get null, please look at my iteration in the for loop line. I am curious to why im getting a null value? Any Idea on a fix?
Thank you, Sincerely
*Java Noob
String filename="C:\\Users\\Karanvir\\Desktop\\21days\\players.txt";
File filez=new File(filename);
BufferedReader br;
String[] playerNames = null;
int counterOfReadLines=0;
try {
br = new BufferedReader(new FileReader(filez));
System.out.println(br.readLine());
counterOfReadLines=counterOfReadLines+1;
while(br.readLine() != null){
System.out.println(br.readLine());
counterOfReadLines=counterOfReadLines+1;
playerNames=new String[counterOfReadLines];
}
for(int i=0;i<playerNames.length;i++){
playerNames[i]=br.readLine();
}
br.close();
Rob Gronkowski 48
Zach Ertz 34
Travis Kelce 29
Evan Engram 15
Jimmy Graham 12
Cameron Brate 10
Delanie Walker 9
Kyle Rudolph 6
Austin Seferian-Jenkins 6
Jack Doyle 6
Hunter Henry 5

while(br.readLine() != null){
System.out.println(br.readLine());
counterOfReadLines=counterOfReadLines+1;
playerNames=new String[counterOfReadLines];
}
for(int i=0;i<playerNames.length;i++){
playerNames[i]=br.readLine();
}
This just doesn't work at all:
while(br.readLine() != null){
is reading a line, checking if it is null, then discarding it.
System.out.println(br.readLine());
is reading another line, printing it, then discarding it.
playerNames=new String[counterOfReadLines];
is creating a new array, filled with nulls.
You never put anything into the array.
Now:
for(int i=0;i<playerNames.length;i++){
playerNames[i]=br.readLine();
}
OK, so you go back and try to read the right number of items from the BufferedReader. However, the reason you stopped the previous loop is because br.readLine() returned null, and that's because you reached the end of the stream.
You've already read all the data there is to be read here, so you just read a null on each iteration, and put that into the array element (which already is already set to null).
Instead, use a List<String>, which can grow - arrays cannot - and put items into that:
List<String> playerNames = new ArrayList<>();
String line;
// This reads a line, and stores it in a variable, so you can use
// the String you read inside the loop body.
while ((line = br.readLine()) != null) {
System.out.println(line);
// Don't need counterOfReadLines, just use playerNames.size().
playerNames.add(line);
}

The normal usage of readLine is:
List<String> lines = new ArrayList<>();
for (;;) {
String line = br.readLine();
if (line == null) { // End of input reached.
break;
}
System.out.println(line);
lines.add(line);
}
for (String line : lines) {
System.out.println(line);
}
Arrays do not grow, so better use an ArrayList.

Related

assigning properties to strings in text file

Hopefully my explanation does me some justice. I am pretty new to java. I have a text file that looks like this
Java
The Java Tutorials
http://docs.oracle.com/javase/tutorial/
Python
Tutorialspoint Java tutorials
http://www.tutorialspoint.com/python/
Perl
Tutorialspoint Perl tutorials
http://www.tutorialspoint.com/perl/
I have properties for language name, website description, and website url. Right now, I just want to list the information from the text file exactly how it looks, but I need to assign those properties to them.
The problem I am getting is "index 1 is out of bounds for length 1"
try {
BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"));
while (in.readLine() != null) {
TutorialWebsite tw = new TutorialWebsite();
str = in.readLine();
String[] fields = str.split("\\r?\\n");
tw.setProgramLanguage(fields[0]);
tw.setWebDescription(fields[1]);
tw.setWebURL(fields[2]);
System.out.println(tw);
}
} catch (IOException e) {
e.printStackTrace();
}
I wanted to test something so i removed the new lines and put commas instead and made it str.split(",") which printed it out just fine, but im sure i would get points taken off it i changed the format.
readline returns a "string containing the contents of the line, not including any line-termination characters", so why are you trying to split each line on "\\r?\\n"?
Where is str declared? Why are you reading two lines for each iteration of the loop, and ignoring the first one?
I suggest you start from
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
and work from there.
The first readline gets the language, the second gets the description, and the third gets the url, and then the pattern repeats. There is nothing to stop you using readline three times for each iteration of the while loop.
you can read all the file in a String like this
// try with resources, to make sure BufferedReader is closed safely
try (BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"))) {
//str will hold all the file contents
StringBuilder str = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
str.append(line);
str.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
Later you can split the string with
String[] fields = str.toString().split("[\\n\\r]+");
Why not try it like this.
allocate a List to hold the TutorialWebsite instances.
use try with resources to open the file, read the lines, and trim any white space.
put the lines in an array
then iterate over the array, filling in the class instance
the print the list.
The loop ensures the array length is a multiple of nFields, discarding any remainder. So if your total lines are not divisible by nFields you will not read the remainder of the file. You would still have to adjust the setters if additional fields were added.
int nFields = 3;
List<TutorialWebsite> list = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader("tutorials.txt"))) {
String[] lines = in.lines().map(String::trim).toArray(String[]::new);
for (int i = 0; i < (lines.length/nFields)*nFields; i+=nFields) {
TutorialWebsite tw = new TutorialWebsite();
tw.setProgramLanguage(lines[i]);
tw.setWebDescription(lines[i+1]);
tw.setWebURL(lines[i+2]);
list.add(tw);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
list.forEach(System.out::println);
A improvement would be to use a constructor and pass the strings to that when each instance is created.
And remember the file name as specified is relative to the directory in which the program is run.

Reading from file to array but last line overrides all other lines [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
So I wanted this to be my last resort because I did enough progress with doing the main code and I was only to come here if nothing else worked.
String line = "";
try
{
BufferedReader br = new BufferedReader (new FileReader("league.txt"));
FootballClub club = new FootballClub();
while ( ( line = br.readLine() ) != null )
{
String[] FC = line.split(",");
club.setName(FC[0]);
club.setLocation(FC[1]);
club.setMatchesPlayed(Integer.parseInt(FC[2]));
club.setWins(Integer.parseInt(FC[3]));
club.setDraws(Integer.parseInt(FC[4]));
club.setLosses(Integer.parseInt(FC[5]));
club.setGoalsScored(Integer.parseInt(FC[6]));
club.setGoalsAgainst(Integer.parseInt(FC[7]));
club.setGoalDifference(Integer.parseInt(FC[8]));
club.setPoints(Integer.parseInt(FC[9]));
league.add(club);
}
br.close();
}
catch (FileNotFoundException e) { }
catch (IOException e){ }
This is my code from reading from a text file into array. The text file is as follows:
Chelsea,London,0,0,0,0,0,0,0,0
WestHam,London,0,0,0,0,0,0,0,0
The problem is that when I test the program, two clubs get added to the array however the values for the first line get overridden by the second line. I have been trying to get one line added first then the second until there is no line but I seem to be lucking out. I have been looking everywhere to try and fix it but no luck and it does seem like an easy fix but I'm burned out and can't find it. Any pointers and suggestions would be appreciated.
You need to create a new instance of the class on each iteration, otherwise you keep setting properties on the same object, so only the last line will be stored.
while ((line = br.readLine()) != null){
String[] FC = line.split(",");
FootballClub club = new FootballClub();
//...
}

How to print a file's contents backwards?

I have an assignment where I need to read a file's contents in reverse, like this:
Original:
This is how you reverse a file, 10
New:
10 ,file a reverse you how is This
Here's the code I have:
public static void main(String [args]{
Path file = Paths.get("C:\\Java\\Sample.txt");
InputStream input = null;
ArrayList<String> words = new ArrayList<String>();
try{
input = Files.newInputStream(files);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String s;
while((s = reader.readLine()) != null)
words.add(s);
for(int i = words.size() - 1; i >= 0; i--){
System.out.print(words.get(i));
}
catch(Exception e){
System.out.println(e);
}
}
Sorry if the formatting is off. The program simply reads the file in original form. What am I doing wrong? Can anyone explain what I need to have this print backwards? My textbook doesn't explain anything.
Also, I realize that my catch block is possibly too broad. I'll work on that.
EDIT: I forgot to add the ArrayList code when typing this out. It exists already in my original program.
Thank you
while((s = reader.readLine()) != null)
words.add(s);
The second line implies that s holds words, but the first line reads a line at a time. You need to read a word at a time, or split the lines into words.

Get data from a specific line in text file using BufferedReader

I am currently building an application that is extracting values from a text file inside a project. Somehow managed extract data from specific lines but don't seem to get the right one.
Here is the code:
private String getInputsFromATextFile(int item) throws FileNotFoundException {
InputStream is = this.getResources().openRawResource(R.drawable.input);
StringBuilder builder = new StringBuilder();
int lineNo = 0;
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine()) != null){
lineNo++;
if(lineNo == item){
builder.append(reader.readLine());
}
}
reader.close();
}
catch (IOException e){
e.printStackTrace();
}
return builder.toString();
}
And here are the text file contents:
20.45
21.65
1
225
4102
401
3
3
6
1
196.41
64.11
7
3
5
2
144.01
3
452.33
12
701.33
33
78.12
12
123.90
4
25.00
10
6.51
30.98
2.50
Spiderman
100.00
90
150.00
100
10
34
12
James
1267
Joshue
401
Christelle
3050
Ryan
888
Hanna
5
13
24
9
5
3
50
Suppose we assign a certain line number in a parameter. This method returns the exact next data from which the line number is assigned. Although, maybe I can adjust to the output that it always returns (lineNo + 1), but if in case I assigned '0' (zero) in the parameter, it instead returns null. Why is that so? I must be missing something really important.
That's because you're reading the line again in the statement builder.append(reader.readLine()).
Notice that you've already read it in while loop.
So, the correct statement would be:
builder.append(line);
Don't read it again when appending it. Use :
builder.append(line);
Also, if you want it to be 0 indexed, you should increment lineno after comparing it.
if(lineno == item)
{
}
lineno ++;
If you do it before comparision, it will never be 0 and hence returns a null .
Is that optimal?
If it just a one time retireval Yes.
If you use it again and again - No, everytime you want data from the line, you need to traverse the whole file till that line.
One way you can do is to store it in an ArrayList.
InputStream is = this.getResources().openRawResource(R.drawable.input);
ArrayList<String> list = new ArrayList();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine()) != null){
list.add(line);
}
reader.close();
}
catch (IOException e){
e.printStackTrace();
}
getLineFromFile(list, 10);
Store all the strings in an arrayList and then retrieve them.
public String getLineFromFile(ArrayList<String> list, int lineNo);
{
return list.get(lineNo - 1);
}

How to read a specific line in a text file and return a part of it?

I have several strings in a file where I am supposed to stop and read the values from those strings. For example:
This is the first line
#1 stop = 300
This is the third line
This is the 4th line
#2 stop = 400
This is the 6th line
I need to stop at #1 and extract the value 300 from there. Then I have to stop at #2 and extract 400, and so on.
I am VERY new to Java and can't figure out what is wrong with my code. (I haven't gotten to extracting the values yet):
public static void main(String[] args) throws IOException {
//read
File fromFile = new File("in.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(fromFile));
String line;
String firstHandler="";
while ((line = bufferedReader.readLine()) != null) {
bufferedReader.readLine();
if (firstHandler.startsWith("#1")){
System.out.println(firstHandler);
String[] parts = firstHandler.split("=");
System.out.println(Arrays.toString(parts));
}
break;
}
System.out.println(line);
bufferedReader.close();
}
}
At this point it only prints the first line, which is not at all what I need. Can anyone explain to me how this should be done in the right way?
The errors are in these 4 lines:
String firstHandler="";
while ((line = bufferedReader.readLine()) != null) {
bufferedReader.readLine();
if (firstHandler.startsWith("#1")){
You read one line from inside the while statement. And for each line read, you enter the block. But inside this block, you read yet another line.
And then, what you compare with "#1" is not the line that you have just read, but firstHandler, which is initialized as an empty string once, and never modified. The code should be:
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#1")) {
The reader should also be closed in a finally block, but that's another matter.
First of all, as pointed out in the comments, you need to match lines starting with a #, since there are multiple lines beginning with # but having a different second character.
Next, you need to check the value of the line that you are reading to check for the # character. So, you can get rid of the firstHandler variable and use the line variable instead.
Finally, you need to get rid of the break statement, since that causes the loop to exit after the first line itself. That is the reason you only see the first line on the screen.
Therefore, your code can be changed to something like this:
while ((line = bufferedReader.readLine()) != null)
{
if (line.startsWith("#"))
{
System.out.println(line);
String[] parts = line.split("=");
System.out.println(Arrays.toString(parts));
}
}

Categories