indexOf problem
My codes are asking user to input company name and then search that company name in text file by using indexOf
Got error message "
java.lang.NullPointerException
at java.lang.String.indexOf(String.java:1564)
at java.lang.String.indexOf(String.java:1546)
at javaapplication4.Main.main(Main.java:56)
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(isr);
String s =null;
System.out.println("Enter the name of company or date of order");
try{
while ((s=br.readLine())!=null){
File file =new File("C:\\month.txt");
FileInputStream fis =null;
BufferedInputStream bis =null;
BufferedReader bufferedReader =null;
String record;
int recCount=0;
int p=0;
s=br.readLine();
s= s.trim();
try{
fis =new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis =new BufferedInputStream(fis);
bufferedReader =new BufferedReader(new InputStreamReader(bis));
while((record=bufferedReader.readLine()) !=null){
//p=record.indexOf("Company A");
p=record.indexOf(s);
if (p != -1){
recCount++;
//System.out.println(p);
System.out.println(record);
}
}
Can anybody tell why its problem using indexOf (s) where this s=br.readLine(); which is input entered by user?
[2449 byte] By [
seemapa] at [2007-11-26 12:25:43]

Hi Just See this this is working fine
import java.io.*;
class Files
{
public static void main(String[] args) throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = null;
System.out.println("Enter the name of company or date of order");
File file = new File("month.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedReader bufferedReader = null;
String record;
int recCount=0;
int p=0;
s=br.readLine();
s= s.trim();
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
bufferedReader = new BufferedReader(new InputStreamReader(bis));
while((record=bufferedReader.readLine()) != null)
{
p=record.indexOf(s);
if (p != -1)
{
recCount++;
System.out.println(record);
}//if
}//while
}
}
these are contents of month.txt
A 1
B 2
Because your code makes no sense?
Your first while loop reads a line from br, and breaks if it is null, but then inside that loop, you do a s = br.readLine() again. That second readline can be null, yet the loop won't terminate at that point. Then you use that possibly null value as an argument tot he indexOf inside that nested while loop, thus causing a NPE to be thrown. Get rid of the s=br.readLine() call and it should work, but I haven't read thru the entire block of code, so there may be more problems.
~Tim