We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › searching arraylist
Pages: 1 2 3 
searching arraylist (Read 2706 times)
searching arraylist
Mar 27th, 2009, 8:03am
 
Hello, i was wondering how to search an array list. im putting data into the arraylist and want to to be able to have certain words trigger different things

like if a sentence came in and said "the sea is blue" the word blue would turn that text colour to blue. a very crude example i know

any help appreciated
Re: searching arraylist
Reply #1 - Mar 27th, 2009, 8:43am
 
I think the best (?) and perhaps only way is to iterate on the array list, get the stored string, search the word there.
To find if a word is in a string, you can use sentence.indexOf(word);
Re: searching arraylist
Reply #2 - Mar 27th, 2009, 9:01am
 
A quick way to check might be sentence.contains(word);  This would return a true / false.
Re: searching arraylist
Reply #3 - Mar 27th, 2009, 12:09pm
 
Ah, I overlooked contains. I see it have been introduced in Java 1.5, that's why indexOf is much more well known.
I see also that contains' code is actually using indexOf. But well, as you point out, it is more convenient (more readable, more succint) for just presence checking.
Re: searching arraylist
Reply #4 - Apr 20th, 2009, 4:06am
 
does anyone have an example of how sentence.contains(word) would look inline ?

Re: searching arraylist
Reply #5 - Apr 20th, 2009, 5:25am
 
You might try this -
Code:

import java.util.*;

ArrayList words;
String sentence;
String word2find;

void setup(){
 sentence = "Mary had a little lamb";
 words = getWords(sentence);
 word2find = "little";
 if(words.contains(word2find))
   println("Found " + word2find);
 else
   println("Can't find " + word2find);

}

ArrayList getWords(String s){
 String[] w1 = s.split(" ");
 ArrayList w2 = new ArrayList();
 for(int i = 0; i < w1.length; i++){
   w2.add(w1[i]);
 }
 return w2;
}
Re: searching arraylist
Reply #6 - Apr 20th, 2009, 9:22am
 
ok think i understand that, next question is that if i want to pull out the sentence that the word comes from how would i display that instead of just the work?
Re: searching arraylist
Reply #7 - Apr 20th, 2009, 1:58pm
 
I have assumed that your are searching some text with multiple sentences separated by full stops. If that is the case then this works
Code:

import java.util.*;

String[] sentences;
ArrayList words;
String book;
//String sentence;
String word2find;

void setup(){
 book = "Mary had a little lamb. ";
 book += "Its fleece as white as snow. ";
 book += "Every where Mary went it was sure to go. ";

 word2find = "Mary";

 // Split the book into sentences
 sentences = book.split("[.]");
 // Search each sentence
 for(int i = 0; i < sentences.length; i++){
   words = getWords(sentences[i]);
   if(words.contains(word2find))
println("Found " + word2find + " in " + sentences[i]);
 }
}

ArrayList getWords(String s){
 String[] w1 = s.split(" ");
 ArrayList w2 = new ArrayList();
 for(int i = 0; i < w1.length; i++){
   w2.add(w1[i]);
 }
 return w2;
}

Re: searching arraylist
Reply #8 - Apr 21st, 2009, 2:56am
 
well the information I'm looking through is text (sms) messages that have been sent to a database which i am reading into processing.

i guess i could add a full stop to the info as it is placed into the db

would that be reccomended
Re: searching arraylist
Reply #9 - Apr 21st, 2009, 3:12am
 
PhiLho  wrote on Mar 21st, 2009, 9:56pm:
Code:
import de.bezier.data.sql.*;
import java.sql.Timestamp;

static final String TABLE_NAME = "p5_messages";

static final int CHECK_INTERVAL = 5; // seconds
int lastCheck = - CHECK_INTERVAL - 1;
Timestamp lastTimestamp = new Timestamp(0L);
static final int MESSAGE_DISPLAY_DURATON = 10; // seconds
int lastMessageDisplayedIndex;
int lastMessageDisplayDuration = MESSAGE_DISPLAY_DURATON;
static final int MESSAGE_DISPLAY_NB = 4;

MySQL mysql;
PFont fontHeader;
PFont fontMessage;

ArrayList messageList = new ArrayList();

void setup()
{
size(400, 700);
smooth();
fontHeader = createFont("Arial", 30);
fontMessage = createFont("Verdana", 16);

Connect();
//~ Message m = GetMessage(2);
//~ ShowMessage(m);
}

void stop()
{
println("Stopping connection");
mysql.close();
}

void draw()
{
int time = millis() / 1000;
if (time - lastCheck > CHECK_INTERVAL)
{
lastCheck = time;
// On second though, no need for this!
//~ int newMessageNb = CheckNewMessages(lastTimestamp);
int newMessageNb = GetNewMessages(lastTimestamp);
int totalMessageNb = messageList.size();
println("New messages: " + newMessageNb + ", total: " + totalMessageNb);
if (newMessageNb > 0)
{
Message lastMessage = (Message) messageList.get(totalMessageNb - 1);
lastTimestamp = lastMessage.m_date;
}

background(#225577);
textFont(fontHeader, 36);
fill(#FFCC88);
text("Message Board", 10, 36);
ShowCount();
if (totalMessageNb == 0)
return;

lastMessageDisplayDuration -= CHECK_INTERVAL;
if (lastMessageDisplayDuration <= 0 && lastMessageDisplayedIndex < totalMessageNb - 1)
{
lastMessageDisplayedIndex++;
}
for (int i = 0; i < MESSAGE_DISPLAY_NB; i++)
{
int idx = 1 + lastMessageDisplayedIndex - MESSAGE_DISPLAY_NB + i;
if (idx < 0)
continue;
Message m = (Message) messageList.get(idx);
ShowMessage(m, i);
}
}
}

void ShowCount()
{
textFont(fontHeader, 20);
fill(#AACC88);
text("Number of messages: " + GetCount(), 10, 60);
}

void ShowMessage(Message m, int pos)
{
int yPos = 100 + pos * 150;
textFont(fontMessage);
fill(#FF8855);
text(m.m_author, 10, yPos);
fill(#8855FF);
text(FormatHour(m.m_date), 100, yPos);
fill(#00EE77);
text(m.m_message, 10, yPos + 10, width - 2, 200);
}

/*=== Message Class ===*/

class Message
{
String m_author;
String m_message;
Timestamp m_date;
int rank;

Message(String author, String message, Timestamp date)
{
m_author = author;
m_message = message;
m_date = date;
rank = messageList.size();
}
}

/*=== MySQL Section ===*/

void Connect()
{
mysql = new MySQL(this, "localhost", "tests", "PhiLho", "Foo#Bar");
if (!mysql.connect())
{
println("Cannot connect to database!");
exit();
}
}

int GetCount()
{
mysql.query("SELECT COUNT(*) FROM " + TABLE_NAME);
mysql.next();
return mysql.getInt(1);
}

int CheckNewMessages(Timestamp previousDate)
{
mysql.query("SELECT COUNT(*) FROM " + TABLE_NAME +
" WHERE date_added > '" + FormatTimestamp(previousDate) + "'"
);
mysql.next();
return mysql.getInt(1);
}

int GetNewMessages(Timestamp previousDate)
{
String query = "SELECT creator, message, date_added FROM " + TABLE_NAME +
" WHERE date_added > '" + FormatTimestamp(previousDate) + "'";
println(query);
mysql.query(query);
int newMessageNb = 0;
while (mysql.next())
{
String a = mysql.getString(1);
String m = mysql.getString(2);
Timestamp d = mysql.getTimestamp(3);
Message msg = new Message(a, m, d);
messageList.add(msg);
newMessageNb++;
}
return newMessageNb;
}

Message GetMessage(int idx)
{
mysql.query("SELECT creator, message, date_added FROM " + TABLE_NAME +
" WHERE id=" + idx
);
mysql.next();
String a = mysql.getString(1);
String m = mysql.getString(2);
Timestamp d = mysql.getTimestamp(3);
return new Message(a, m, d);
}

String FormatHour(Timestamp ts)
{
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(ts);
}

String FormatTimestamp(Timestamp ts)
{
DateFormat formatter = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
return formatter.format(ts);
}

Some code there isn't used but can be interesting to see.


would i be able to add the search arraylist to this code easily enough? what I'm aiming to do is to have a certain word trigger a different style (font size colour) and apply it to the whole sentence.
Re: searching arraylist
Reply #10 - Apr 21st, 2009, 3:49am
 
You don't need to split the sentence. Just use contains() as advised.
Quark split the data by sentences, but I suppose you actually mean "sentence" by "whole short message", no?

OK here is a 5 minutes sketch to illustrate its usage:
Code:
class ColorNameAndValue
{
String name;
color value;

ColorNameAndValue(String n, color c)
{
name = n;
value = c;
}
}

ColorNameAndValue[] triggers =
{
new ColorNameAndValue("blue", #0000FF),
new ColorNameAndValue("green", #00FF00),
new ColorNameAndValue("red", #FF0000),
new ColorNameAndValue("cyan", #00FFFF),
new ColorNameAndValue("magenta", #FF00FF),
new ColorNameAndValue("yellow", #FFFF00),
new ColorNameAndValue("black", #000000),
new ColorNameAndValue("white", #FFFFFF)
};

String[] sentences =
{
"Black Magic Woman",
"Blue Velvet",
"Yellow Submarine",
"White Christmas",
"Cyanide and Hapiness",
"Brown Sugar",
"Black Belt Ninja",
"The Yellow Brick Road",
"The Blues Brothers",
"Greensleeves",
"The Red Line",
"Magenta is rare in song and film names..."
};

void setup()
{
size(300, 500);
background(200);
PFont f = createFont("Arial Bold", 15);
textFont(f);
for (int s = 0; s < sentences.length; s++)
{
String sentence = sentences[s];
color col = #7F7F7F;
for (int c = 0; c < triggers.length; c++)
{
if (sentence.toLowerCase().contains(triggers[c].name))
{
col = triggers[c].value;
break;
}
}
fill(col);
text(sentence, 10, 20 * (s + 1));
}
}
Re: searching arraylist
Reply #11 - Apr 21st, 2009, 5:20am
 
would that framework work for instance using the word paint would make a spray paint blob appear and dripdown instead of the message instead ?
Re: searching arraylist
Reply #12 - Apr 21st, 2009, 5:28am
 
This solution is much neater than using the ArrayList.

The reason I split the sentence into an ArrayList was that this discussion started with
"Hello, i was wondering how to search an array list..."

I misunderstood the problem.
Re: searching arraylist
Reply #13 - Apr 21st, 2009, 5:41am
 
well my actuall info is being populated into an arraylist so which option would be best ?
Re: searching arraylist
Reply #14 - Apr 21st, 2009, 5:46am
 
Quote:
I misunderstood the problem.

Yes, sometime getting a good specification from the user is the hard part for the programmer... Wink

Quote:
using the word paint would make a spray paint blob appear and dripdown instead of the message instead

Can be done. For example I would define the class to hold a name and an object of a given interface, make several paint classes implementing this interface, and initializing the array with them.
Then instead of doing fill(col); text(...);, call the paint method of the related class (I feel some code must be coming to illustrate that...).

Quote:
my actuall info is being populated into an arraylist

I understood that your sentences are in an array list, that's why I initially wrote to walk the arraylist (like I walk the array in my sample) and search for each sentence.
Pages: 1 2 3