problems with equals method.
When i use the following code, the equals mehod return true if i use numbers , if i use a string as given in the code the method always returns false what could be the reason. The store.txt file contains the following lines as given. If i give the equal string as 1000 the match is produced and if i give as kp or kkn the output always states no match .
store.txt
kp
1000
kkn
500
[code=java]
import java.io.*;
class home
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("store.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int value=0;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
if(strLine.equals("kp"))
{
System.out.println("Match found");
value = Integer.parseInt(strLine);
value=value+100;
System.out.println(value);
}
else
System.out.println("No match");
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
[/code=java]
Plz help me out
Re: problems with equals method.
Add a println statement just before the equals statement and print out the String being compared in the equals method so you can see what the computer is seeing. Be sure to add delimiters on both sides fo the String:
(">" + theString +"<" ):
That should explain what is happening.
Post the console contents from when you execute the code:
To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'
Paste here.
Check you code tags. Use the #icon above the input box
Re: problems with equals method.
Try using a
Code java:
strLine = (br.readLine().trim())
The trim method as part of the String library will remove any whitespace characters on the line you read into the buffer. Hope this helps :-?