Hi

I am a novice working with Java and the eclipse IDE. What I want to read words from a text file, store it as a list converting it to some uniform case. Then I input some word/sentence from keyboard and check whether it is present in the file.

Well my reading from file is working fine with BufferedReader and case conversion too is ok and I am displaying file contents.
I tried the following with the substring finding, but somehow my truth flag is forever false.

boolean truth = link [index].contains (name);

where I calculated index

int index;
char achar = name.charAt(0);
index = achar - 'a';

where "name" is the string input from key board, ie to be searched and "link" is my original list (text file)

Whats wrong with the truth flag statement?

Dani AI

Generated

Brief diagnosis and quick checklist based on the code and prints you posted: the membership test will fail if the stored strings are not byte-for-byte equal to the search string or if they were inserted into a different bucket. Common causes seen in cases like this are (a) invisible characters or different normalization (extra whitespace, carriage returns or a UTF-8 BOM) left in the stored strings, (b) your file-reading loop lumping many words into a single read (so everything ends up in bucket 0), or (c) computing an index from a non-letter first character. was right that contains() relies on equals; for String that is fine — the failure is in how the strings are read/normalized or placed.

Minimal debugging steps to run now (no code copy from your posts):

  • When inserting each word, print it enclosed in delimiters and its first-character codepoint, e.g. show "'<word>' -> 97" so you can spot extra characters or a BOM.
  • Print the computed bucket index for every inserted word and verify it ranges 0..25.
  • If the file can contain multiple tokens per line, split the line into tokens before inserting.

A safer approach (example) is to normalize everything and use a HashSet for membership checks (faster and simpler than 26 lists). The example below shows the intent (modern try-with-resources, trim, lower-case, strip initial BOM if present) — adapt to your Java version:

try (BufferedReader r = new BufferedReader(new FileReader("inp.dat"))) {
  Set<String> words = new HashSet<>();
  String line;
  while ((line = r.readLine()) != null) {
    line = line.trim().toLowerCase();
    if (line.startsWith("\uFEFF")) line = line.substring(1);
    if (!line.isEmpty()) {
      for (String token : line.split("\\s+")) words.add(token);
    }
  }
  // later: boolean found = words.contains(query.trim().toLowerCase());
}

Final notes: avoid using stream.available() as an EOF check and avoid deprecated DataInputStream.readLine(); normalize both stored and query strings (trim + toLowerCase or use equalsIgnoreCase). If you keep the 26-bucket design, validate that you only subtract 'a' when the first character is a lowercase letter (use Character.isLowerCase/isLetter), otherwise skip or route to a fallback bucket. These checks will reveal why your truth flag is always false.

Recommended Answers

All 5 Replies

What kind of Objects are in your list? Are they Strings? if so, contains should work fine, if they are custom made Objects, you will need to override the equals() method of the Object class. You can look into how to do this properly on google; it is fairly simple.

What kind of Objects are in your list? Are they Strings? if so, contains should work fine, if they are custom made Objects, you will need to override the equals() method of the Object class. You can look into how to do this properly on google; it is fairly simple.

Hi,

Each object of the list is string, right.

is there trouble using readline(), available() (deprecated functions )? I switched to FileinputStream and DataInputStream from BufferedReader because I got stuck using available() function with BufferedReader.


while (in.available()!= 0){
name = in.readLine();
name = name.toLowerCase();
System.out.println( name );
char achar = name.charAt(0);
link [achar -'a'].add(name);

}

Is this bit of reading from file, converting it to some case and storing it in the list ok?
With BufferedReader what modification for available needed?
Thanks,

If you are looking for suggestions on how to read from the file (and haven't already settled on an option), keep in mind that there are many options out there. I recommend using Scanner. You can create a File object and feed it to the Scanner Object, then use Scanner's methods to read from the File. Quick example for you:

File f = new File("c:/file/pathname");
Scanner readFromFile = new Scanner(f);
String element = readFromFile.next();

go read the scanner documentation on google to find out how to use its methods.

If you are looking for suggestions on how to read from the file (and haven't already settled on an option), keep in mind that there are many options out there. I recommend using Scanner. You can create a File object and feed it to the Scanner Object, then use Scanner's methods to read from the File. Quick example for you:

File f = new File("c:/file/pathname");
Scanner readFromFile = new Scanner(f);
String element = readFromFile.next();

go read the scanner documentation on google to find out how to use its methods.

hi
I am ok with readline. I am trying variations since that truth flag value is forever "false".

boolean truth = link [index].contains (name);

And my list object is string, and so am backtracking whether anything wrong with my file reading and storing into list. I am not finding out where I have messed up.

Thanks,

This is the test class of the discussion:

public class testclass
{
 	public void testfunction()
	{
		LinkedList[] link=new LinkedList[26];
	    String s[] = new String[10];
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in) );
	    String name = new String();
	    for(int i=0;i <26; i++)
	    link[i] = new LinkedList();
	    FileInputStream fin;
	    DataInputStream in;
	 	try
	 		{
	 			// Open an input stream
	 			// For now, hardcoded to inp.dat
	 			fin = new FileInputStream ("inp.dat");
	 			in = new DataInputStream(fin);
	 			//BufferedReader in = new BufferedReader(new InputStreamReader(fin));
	 			System.out.println("**** Elements read from file *****");
	    		while (in.available()!= 0)// In a loop read from a file
	    		{ 
	    				name = in.readLine();
	    				// and insert into linked list after converting to lower case
	    				name = name.toLowerCase(); 
	    				//print
	    				System.out.println( name );
	    				char achar = name.charAt(0);
	    				link [achar -'a'].add(name);
	    	
	    		}
	    		System.out.println("**** End of elements ****");
	    		// Close input stream
	    		fin.close();		
	 		}
			// Catches any error conditions
		catch(IOException e)
			{
				System.err.println ("Unable to read from file");
				System.exit(-1);
			}
			// Now read from keyboard a string and find it if it is there
			System.out.println("**** Enter the String you want to search   ");
		 try 
		 	{
		    name =  br.readLine();
		    }
		 catch(IOException ioe1)
			{
				System.out.println(ioe1.getMessage());
				ioe1.printStackTrace();
			}
		    System.out.println("The content entered is " + name);
		    name = name.toLowerCase();
		    System.out.println("Converted string " + name);
		    int index;
		    char achar = name.charAt(0);
		    System.out.println("first char " + achar);
		    boolean truth;
		    index = achar - 'a';
		    System.out.println("Calculated index " + index);
		    //Is this a valid display statement?
		    System.out.println("link[index]  " + link[index]);
		    //Prints entire list if index=0 or prints []for any other value of index
		    //How to print the list from given index value?
		    truth = link [index].contains (name);
		    System.out.println("Truth flag " + truth);
		    if (truth==true)
		    	System.out.println(name + " is present in the linked list " + index);
		    else
		    	System.out.println (name + " is not present");
	}
}

I have just inserted print here and there just to check. Somewhere I have messed up, not getting where...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.