d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > What's Wrong With My Code?
Add Reply New Topic New Poll
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Sep 25 2020 09:28pm
Code
package com.ferfykins.exercises;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {

public static void main(String[] args) {

String path = "search.txt";

readFile("purple", path);


}



public static void readFile(String searchItem, String path) {
String line;
int counter = 1;

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while((line = br.readLine()) != null){
String input = br.readLine();
String[] data = input.split(" ");

for(String words : data) {
if (words.equals(searchItem)) {
System.out.println(searchItem + " was found on line: " + counter);
}
}
counter++;

}


} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


}



}






i get these exceptions... not sure what;s causing them or how to fix:
Code
Exception in thread "main" java.lang.NullPointerException
at com.ferfykins.exercises.Main.readFile(Main.java:28)
at com.ferfykins.exercises.Main.main(Main.java:14)





also the code isn't working as it should..... basically i search a text file for a given string, and it should report all line numbers where that string occured..... this sometimes works and sometimes doesn't.... well, it doesn't work completely, sometimes it only gives one instance, not all instances of the string.












Member
Posts: 1,304
Joined: Jul 8 2012
Gold: 0.00
Sep 25 2020 10:31pm
Code
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while((line = br.readLine()) != null){ //Reads a line, assigns it to line.
String input = br.readLine(); //Reads the next line, assigns it to input.


You read the line into the "line" variable - don't do anything with it, then read the next line into the "input" variable and do something with it. Effectively, reading every other line.

The exception is because since you read a line in the condition for the while loop, there will be a line there, but then you read it again into input and there will not be an additional line - causing the null exception.

Attempt this modification:

Code
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while((line = br.readLine()) != null){
String[] data = line.split(" ");


This post was edited by Kippet on Sep 25 2020 10:36pm
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Sep 25 2020 10:53pm
Yeah thanks man, a friend of mine actually said the same thing and i got it working before i read this, but still ty for helping <3 :)
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll