|
Bangladeshi Softwares
|
| Home - Download - Codes & Tutorials - Bangla IT Bibhag - Mobile - About Me |
Determining the longest word in an Applet with StringTokenizer
Step-1:
This code snippet utilizes the java.util.StringTokenizer class to determine the longest word in an Applet. Some methods may be deprecated in the latest version of Sun's JDK (this code was in the download section and originally written in the year 2003). I used JDK 1.3.1_01 to compile this class. Open your favorite text editor and type the code below:
/*
* Author: Ahsanul Haque Shovon
* Email: ahsanul.haque.shovon@gmail.com / ahsanul_haque_shovon@yahoo.com
* Web: http://shovon.110mb.com
*/
import java.util.StringTokenizer;
import java.awt.*;
import java.awt.event.*;
public class FindLongestWord extends
java.applet.Applet implements ActionListener
{
Label lb;
TextArea ta;
Button btn;
Button btn2;
String longest = "";
StringTokenizer strToken;
int count = 0;
String words[];
public void init()
{
lb = new Label("Enter your phrase");
ta = new TextArea(4, 30);
btn = new Button("Find Longest Word");
btn2 = new Button("New Phrase");
add(lb);
add(ta);
add(btn);
add(btn2);
btn.addActionListener(this);
btn2.addActionListener(this);
btn2.setEnabled(false);
}
public void paint(Graphics g)
{
showStatus(getAppletInfo());
g.drawString("Longest word: " + longest, 20, 170);
g.drawString("Length: " + longest.length(), 20, 190);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == btn)
{
strToken = new StringTokenizer(ta.getText(), " ,.\n\t", false);
count = strToken.countTokens();
words = new String[count];
for(int i = 0; strToken.hasMoreTokens(); i++)
{
words[i] = strToken.nextToken();
}
for(int i = 0; i < words.length; i++)
{
if(words[i].length() >= longest.length())
longest = words[i];
}
repaint();
btn.setEnabled(false);
btn2.setEnabled(true);
}
if(ae.getSource() == btn2)
{
btn.setEnabled(true);
btn2.setEnabled(false);
ta.setText("");
longest = "";
repaint();
}
}
public String getAppletInfo()
{
//You are not authorized to remove the code below
return "İAhsanul Haque Shovon";
//You are not authorized to remove the code above
}
}
Step-2:
Save the above code as "FindLongestWord.java" and use the following command to compile it:
javac -g:none -verbose FindLongestWord.java
And use the following code to embed the class file in a HTML page:
<applet code="FindLongestWord.class" width="300" height="210"> Your browser does not support Java Applets or is not a Java enabled browser. Please download The latest Java plug-in from <a href="http://www.java.com/" target="_new">http://www.java.com</a> </applet>
If you do not want to compile the code for some reason, you can download the pre-compiled FindLongestWord.class file here.
Other Helpful Resources:
http://java.sun.com
http://javaboutique.internet.com
|
©Ahsanul Haque Shovon
All rights reserved
|