I have an array list named myArraylist that contains items of the class named TStas. Tstas has a string variable named st_name. I want to search the array list, looking for the TStas instance whose st_name is equal to the string look for and when found return the position (found places) of the TStas in the array list.
public static List<Integer> findplace_byname(String lookfor){
List<Integer> foundplaces = new ArrayList<>(); //list to place posistions of found items
for(int k=0; k<myArraylist.size(); k++) {
TStas a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#"+a.st_name+"#"+lookfor+ "#"); //just to check if everything is read,
if ((a.st_name).equals(lookfor)){
foundplaces .add(k);
}
}
return foundplaces;
}
My problem is that the code fails to detect the equality when comparing to the a.st_name of the first item in myArraylist.
For example:
if I have in myarrailist an item with a.st_name=S9, an item with a.st_name=K9 and another with a.st_name=G4. When lookfor is K9 or G4 all is ok. When searching for the first item in the array having a.st_name=S9 the code fails to "see" the equality.
I am using the showMessageDialog to check that the variable is realy read and it is so. Also I tried to delete or change the 1st item in the arraylist, but the same problem goes on: The 1rst item is not found.
What is happening here?
EDIT
I used the trim() to remove any possible spaces but nothing changed. I then used .length() on the "trimed" string to get the length of each string to be compared and I found that for some reason the 1st element while being "S9" without any spaces has a length of 3!! Is it possible that some king of character is hidden? (I have no idea, a paragraph character or what?)
There is no issue in your current code, check this code your self.
List<Integer> foundplaces = new ArrayList<>();
List<String> myArraylist=new ArrayList<>();
myArraylist.add("S9");
myArraylist.add("K9");
myArraylist.add("G4");
for(int k=0; k<myArraylist.size(); k++) {
String a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#" + a + "#" + "S9" + "#");
if ((a).equals("S9")){
foundplaces .add(k);
System.out.println(k);
}
}
You can see it is working fine. same as your current code.
I found where the problem is.
As I mentioned is a comment I am using a txt file to populate myarraylist . Windows notepad ads automatically to the beginning of text files a BOM character.
(http://en.wikipedia.org/wiki/Byte_Order_Mark.). This character is the problem because I may read "S9" (the first text in the txt file) but it actually is the \65279 character plus "S9".
So using the following when reading the text file that is used to populate myarraylist the problem is solved.
if((int)readingstring.charAt(0)==65279){
readingstring=readingstring.substring(1);
}
Thanks for your help.
Related
Hopefully this will be an easy answer and i'm just overlooking something minor.
Goal: take an array list (which currently contains lines of text from a text file) and set a String variable equal a specified array list position.
At the moment, each line is raw text taken from an Encyclopedia file. I need to be able to remove non alpha's via the .replaceAll function. However, my current program returns a null pointer exception and I'm having some trouble understanding why. I'm fairly new to Java so full answers and explanations are much appreciated.
my code: (My teacher told us to use EasyReader class to make our lives, well easier...)
EasyReader fileIn = new EasyReader("Encyclopedia.txt");
public void createList()
{
String x=fileIn.readLine();
ArrayList<String> list = new ArrayList<String>();
while((!fileIn.eof()))
{
String y=fileIn.readLine();
list.add(y);
}
int count=0;
while(count<list.size())
{
String temp=list.get(count);
temp.replaceAll("[^a-zA-z ]", ""); //null pointer points to this line
temp.toLowerCase(); //and this line
list.set(count, temp);
count++;
}
count=0;
while(count<list.size());
{
System.out.println(list.get(count));
count++;
}
System.out.println(list.size());
while(count<list.size())
{
fileOut.println(list.get(count));
count++;
}
fileOut.close();
}
thanks in advance for the help :)
I think I found your error!
Your while loop should go only to list.size() - 1 not the list.size() you have there. See below:
while(count<list.size()- 1)
{
String temp=list.get(count);
temp.replaceAll("[^a-zA-z ]", ""); //null pointer points to this line
temp.toLowerCase(); //and this line
list.set(count, temp);
count++;
}
Try replacing the two lines that you commented with this instead:
temp = temp.replaceAll("[^a-zA-z ]", "");
temp = temp.toLowerCase();
This is because the replaceAll() method does not change the original string itself, but rather returns a new string with the characters replaced. Same thing with toLowerCase().
You made two mistakes:
1) the replaceAll regex should be temp.replaceAll("[^a-zA-z]", "") (no space after z)
2) you can combine two lines into one method temp.replaceAll("[^a-zA-z]", "").toLowerCase()
3) you need to save your newly returned String to the original variable temp:
temp = temp.replaceAll("[^a-zA-z]", "").toLowerCase();
as #Suitangi mentioned, replaceAll() method does not change the original string itself, but rather returns a new string with the characters replaced. Same thing with toLowerCase().
Hope that helps.
EDIT:
In the last iteration String temp = null;
Add if condition to check it, before regex:
if (temp!=null){
temp = temp.replaceAll("[^a-zA-z]", "").toLowerCase();
list.set(count, temp);
count++;
}
I have a program that is reading a text file that has a list of items, creates an ArrayList consisting of the items it reads, then compares it to a few chosen words. For example, my text file contains this (without the numbering):
book
desk
food
phone
suit
and it reads each one and adds it to an ArrayList. When I tried comparing a String s = "book" to each element in the ArrayList, I find that s is not equal to anything. This is what I have in a method:
for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))
return true;
}
s.contains() doesn't work either. When I print the ArrayList, there's an additional whitespace at the end of each String element. How can I get the comparison to work when s = "book"? Why is there additional whitespace?
Use trim() to remove leading and trailing whitespace.
if (s.equals(list.get(i).trim())
return true;
}
instead of
if (s.equals(list.get(i))
return true;
}
You can use the trim() method of the String class to remove whitespaces in the start and the end of the string.
The whitespaces may be in the file but you didn't notice it. Check with an editor that there are no spaces at the end. To be more sure, check with a hexadecimal editor like hd on unix.
Also, check that the read strings do not contain the line feed character.
I have a problem with a contains (...) method from List <...> class. I'm trying to check if a expression (that is loaded from user input) already exist in a List, but if I entered same name as twice, it said there's nothing same in the List. Please help, there's source code:
boolean checker;
checker = expressions.contains(line[1]);
if (checker == true) {
System.err.println("This expression has already been declared!");
return index;
}
PS: line[1] is a second index in array from main function that stores user-entered line split by whitespaces. (First index of line need to be always 'var', and second is any word that cannot be twice in the List)
Your list may not have exact same string as provided in the input which may be due to white spaces. Try trimming the input and then call contains
checker = expressions.contains(line[1].trim());
I was recently trying to write a script that print out all the permutations of a word in Java. For some reason it only prints out one. I just can't figure it out!
import java.util.*;
public class AllPermutations {
ArrayList<String> letters = new ArrayList<String>();
public void main(){
letters.add("H");
letters.add("a");
letters.add("s");
permutate("",letters);
}
public void permutate(String word, ArrayList<String> lettersLeft){
if(lettersLeft.size()==0){
System.out.println(word);
}else{
for(int i=0;i<lettersLeft.size();i++){
String newWord = new String();
newWord = word+lettersLeft.get(i);
lettersLeft.remove(i);
permutate(newWord, lettersLeft);
}
}
}
}
You need to add the letter you have removed back to the lettersLeft list
public void permutate(String word, ArrayList<String> lettersLeft){
if(lettersLeft.size()==0){
System.out.println(word);
}else{
for(int i=0;i<lettersLeft.size();i++){
String temp = lettersLeft.remove(i);
String newWord = word+temp;
permutate(newWord, lettersLeft);
lettersLeft.add(i, temp);
}
}
}
I haven't tested it, but I think it should work.
The problem is that Java/you are passing by reference, not copy (ArrayList). Therefore once you reach the bottom of your recursion tree, lettersLeft will contain 0 elements, and once you go back up, it will still have 0 elements.
As a side note, StringBuilder/StringBuffer is better at doing string permutation task, since String is immutable, therefore you are wasting a lot of resource creating new Strings, n! to be exact. The difference between the two StringBuilder/Buffer is up to you to discover.
The reason for that is lettersLeft is being passed by reference always. Once you are removing a letter from lettersLeft, it is being permanently removed. So for the first iteration you have "HAS" printed out. once that finishes, the recursion algorithm backs up a level to make the second iteration, but what do you know?? lettersLeft is empty. so it terminates without passing by the if statement causing it not to get another word or permutation. In order to resolve this, create a local copy, just like you did with newWord. Hope that helps.
In this case you are removing the letters from the Arraylist and it gets empty till it reaches the end of first word.. Then after that list size is always zero...Add the removed letter back to the list...........
I would recommend you to use the below link and find good examples of String Permutations as there are both memory efficient and space efficient solutions of String permutations...
http://www.codingeek.com/java/strings/find-all-possible-permutations-of-string-using-recursive-method/
So I am creating a Hash Table that uses an Array of Linked Lists of Arrays. Let me take a second to explain why this is.
So I have previously implemented Hash Tables by creating an Array, and each element of the array is a Linked List. This way I could quickly look up a LL of 450,000 elements by searching for the hash value first in the array, and searching the elements of this LL. I should add that this is a project for school and I cannot just use the Hash Tables that comes with java.
Now I want to do something similar... but I massive have a LL of Arrays that I need to search. Here each element of the LL is line of a text file, which represented by a 4 element array, where each of the 4 elements is a different string that was tab delimited in the input file. I need to be able to quickly access the 2nd, 3rd, and 4th string that was located in each line, and that is now an element of this array.
So What I want is to be able to create an Array of LL of Arrays... first I will find the sum of the ascii values of the second element of an array. Then I will hash the entire array using this value into by Hash Table. Then when I later need to find this element, I will go to the corresponding element of the array, where I have a list of arrays. I will the search for the 2nd value of each array in the list. If i find the one I want, then I return that array, and use the 3rd and 4th element of this array.
As I said, I have this working fine for an Array of LL, but adding the extra dimension of Arrays inside has thrown me off completely. I think it is mostly just figuring out syntax, since I have successfully initialized a Array of LL of Arrays (public static LinkedList[] RdHashLL) so it appears that Java is okay with this in principal. However, I have no idea how to put elements into the Hash Table, and how to read them out.
Below is my code for a ARRAY OF LINKED LISTS that works FINE. I just need help getting it to work for an ARRAY OF LL OF ARRAYS!
public class TableOfHash{
public static LinkedList<String>[] HashLL;
//HASH FUNCTION - Finds sum of ascii values for string
public static int charSum(String s){
int hashVal = 0;
int size = 1019; //Prime Number around size of 8 char of 'z', (8 chars is amoung largest consistantly in dictionary)
for(int i = 0; i < s.length(); i++){
hashVal += s.charAt(i);
}
return hashVal % size;
}
//CREATE EMPTY HASH TABLE - Creates an array of LL
public static void makeHash(){
HashLL = new LinkedList[1019];
for(int i=0; i<HashLL.length; i++){
HashLL[i] = new LinkedList<String>();
}
}
//HASH VALUES INTO TABLE!
public static void dictionary2Hash(LinkedList<String> Dict){
for(String s : Dict){
HashLL[charSum(s)].add(s);
//Finds sum of char vales of dictionary element i,
//and then word at i to the HashLL at point defined
//by the char sum.
}
//Print out part of Hash Table (for testing! for SCIENCE!)
//System.out.println("HASH TABLE::");
//printHashTab();
}
//SEARCH HashTable for input word, return true if found
public boolean isWord(String s){
if(HashLL[charSum(s)].contains(s)){
wordsfound++;
return true;
}
return false;
}
}
I have made some attempts to change this, but for things like if(HashLL[charSum(s)].contains(s)) which searches the LL at the element returned by charsum(s)... I have no idea how to get it to work when it is a LL of Arrays and not of Strings. I have tired HashLL[charSum(s)].[1].contains(s)), and HashLL[charSum(s)][1].contains(s)), and various other things.
The fact that a Google search for "Array of Linked Lists of Arrays" (with quotes) turns up empty has not helped.
Last bit. I realize there might be another data structure that would do what I want, but unless you believe that a Array of LL of Arrays is a totally hopeless cause, I'd like to get it to work as is.
if you have
LinkedList<String[]>[] hashLL;
you can read a specific String like this (one of many ways)
String str = hashLL[outerArrayIndex].get(listIndex)[innerArrayIndex];
To write into the fields, this is possible (assuming everything is initialized correctly).
String[] arr = hashLL[outerArrayIndex].get(listIndex);
arr[index] = "value";