The code below reads from a file ‘helpFile.txt’ and checks for an index represented by ‘#’.
The variable read from the file is stored in the integer c and compared with ‘#’ if the read character is ‘#’ without casting the integer into character. I want to know if the comparison is valid as the compiler is not showing any error.
Also, suppose ‘#’ is found by the program in the file and a string called ‘topic’ immediately follows ‘#’ and it is read using readLine(). Will the ‘String info = br.readLine()’ be just ‘topic’ or ‘#’+’topic’?
Sorry for such a lengthy question. Help much appreciated.
boolean helpOn(String what){
private BufferedReader br;
private String info, topic;
private static PrintWriter pw = new PrintWriter(System.out, true);
int c;
br = new BufferedReader(new FileReader("helpFile.txt"));
try{
do{
//read characters until '#' is found
c = br.read();
if(***c=='#'***){ //check if the character is '#'
pw.println(c);
if((**topic=br.readLine()**).equalsIgnoreCase(what)){ //check if 'what' string is equal to 's' which is the string after '#'
while((info=br.readLine())!=null){ //print info until the end of info
if(info!=null)
pw.println(info);
}
return true;
}
}
}
while(c!=-1);
}
catch(IOException ex){
pw.println("File error.");
ex.printStackTrace();
try{
br.close();
}
catch(IOException e){
pw.println("Error closing file.");
e.printStackTrace();
}
return false;
}
try{
br.close();
}
catch(IOException ex){
pw.println("Error closing file.");
ex.printStackTrace();
}
return false; //topic not found
}
I tried your code, it is woking fine with me, i think u need to check your “helpFile.txt”. i used this in it.
and this is the outout i am getting.
i printed all the three vars u used. c, topic, info.
Now since you are using readline() after reading a character, u must give your “info” from next line in “helpFile.txt”
info will contain anything after topic, as you are using readline() function, it will go to the next line. try with my example.
As soon as “#” is encountered, your var
then
then
If you format your helpFile.txt properly, this will work fine
EDIT
You are using eclipse, and you are saving the file in the “SRC” folder i guess. Save them in your Project folder. just one above the SRC folder and then do this.
it should work.
EDIT2
you don’t need to check info for null twice
If it is NULL, it will automatically come out of loop.
EDIT3
As you used # to mark the begining of the block, you could use anything to mark the end of it. eg
Now, you can modify your while as:
The loop will exit as soon as it gets “$”, and it won’t print anything after that.