Arrays.binarySearch()
Practice question for the SCJP:
Given a properly String array containing five elements, which range of results could a proper invocation of Arrays.binarySearch() produce?
a. 0 through 4
b. 0 thorough 5
c. -1 through 4
d. -1 through 5
e. -5 through 4
f. -5 through 5
g. -6 through 4
h. -6 through 5
Can anyone answer this and give a brief explanation?
-Pengu
BigDaddyLoveHandles wrote:
freakydeaky wrote:
su_penguin wrote:
Can anyone answer this and give a brief explanation?A binary search returns one index position so a range containing one element, like f, should be corrrect.That dash (-) is a minus sign, lad.Okay, I misread this whole thing.
The idea is to come up with the possible return values using this information from binarySearch:
"Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found."
If the key is found the index is returned so that will be an int between 0 and 4.
If the key isn't found (-(insertion point) - 1 is returned. Possible insertion points are ints from 0 to 5, which inserted in the formula gives an int between -1 and -6.
So all in all an int between -6 and 4 can be returned, which makes g correct.
Similar Messages
-
Using java.util.Arrays.binarySearch
Hi,
I tried the following code
import java.util.Arrays ;
class SecondTry {
public static void main(java.lang.String args[]) {
int xyz[] = new int[10];
xyz[0] = 5;
xyz[1] = 6;
xyz[2] = 1;
Arrays.sort(xyz);
System.out.println(Arrays.binarySearch(xyz,5));
i expected to see a result of 1. But i get a 8.
I am sure i must be doing something wrong. But not able to figure out what exactly is wrong. Could somebody help?
TIA,
Babuhi there,
.The output was 8 because u have declared the array size to be 10,so the values which are not assigned would be assigned to zero,so if you change the array size to 3,u would get the desired output :)
cheers
class SecondTry {
public static void main(java.lang.String args[]) {
int xyz[] = new int[3]; //change to three
xyz[0] = 5;
xyz[1] = 6;
xyz[2] = 1;
Arrays.sort(xyz);
System.out.println(Arrays.binarySearch(xyz,5)); -
Hi:
I am tring to learn the methods of the Array class so that I may apply them to the development of a program for searching a phone number list.
I have been able to sort a small list into ascending order but I have not been completely successful with the binarySearch.
If a use a complete string object(ex:"485-2456, tomF") then the search is successful but I want to be able to search for a phone number by name and also I want to do a reverse lookup by phone number.
Can someone point in the right direction to solving the problem?
Thanks.
import java.util.Arrays;
public class ArrayTest
{ public static void main(String[] args)
String [] data = {"485-2456, tomF","455-2456, tomP"};
for (int i = 0; i < data.length; i ++)
{ System.out.println(data );
System.out.println("\n");
Arrays.sort (data);
for (int i = 0; i < data.length; i ++)
{ System.out.println(data [i]);
String key ="485-2456" ;
Arrays.binarySearch(data,key);
System.out.println(Arrays.binarySearch(data,key));i believe that binary search trys to find string that maches to the key you give it, but you have strings that contain two data fields... so you'd probably need to define your own comparition method if you'd like to do it the way you're doing right now.
but i don't know anyone who would recommend to do it the way you have, simplest way might be having two dimentional array...
String[][] data = {{"123", "name1"},{"321", "name2"}};but there could be lot better solutions as well... -
Array.sort() question
I've been looking at Arrays and the Comparator interface. But I don't understand the sorting results:
import java.util.*;
import java.io.*;
class SearchObjArray {
public static void main(String[] args) {
Console con=System.console();
if (con==null) System.exit(1);
String[] sa={"one","two","three","four"};
Arrays.sort(sa);
con.format("The sorted string:%n");
for(String s: sa)
con.format("%s ",s);
//four,one,three,two
con.format("%nA binary search for \"one\": one=%s%n",Arrays.binarySearch(sa,"one"));
//one=1, as expected. The binarySearch found "one" in position 1 of the sorted array.
ReSortComparator rs=new ReSortComparator();
con.format("A binary search for \"one\" using the resort comparator on the string array: one=%s%n",Arrays.binarySearch(sa,"one",rs));
//one=-1<====WHY -1? Why is the insertion point 0?
static class ReSortComparator implements Comparator<String> {
public int compare(String a, String b) {
return b.compareTo(a);
You have to search using the same ordering rules as how the array is sorted. You sorted with one set of rules (String's natural ordering) and searched with a different set of rules (the opposite ordering, as determined by your comparator). That's the same as trying to do a binary search on an unsorted array. Since one of the preconditions of binary search is that the array be sorted, it shouldn't be surprising that you get odd results.
-
Hi:
I need to match the array size with a variable size input file.How would I accomplish this task?
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.Arrays;
@author LearningJava
A telephone lookup program.
@version 1.0
public class Telephone
{ public static void main(String[] args)
{ ConsoleReader console = new ConsoleReader(System.in);
System.out.print ("Enter the file name where the address book"
+ " is stored: ");
String fileName = console.readLine();
if (fileName == null)
System.exit(0);
PhoneBook people [] = new PhoneBook[ARRAY_SIZE];
try
{ FileReader fr = new FileReader(fileName);
BufferedReader in = new BufferedReader(fr);
boolean more = true;
int count = 0;
while (more && count < people.length)
String k = in.readLine();
String v = null;
if (k != null) v = in.readLine();
if (v != null)
people[count] = new PhoneBook(k, v);
count++;
else more = false;
in.close();
catch (IOException exception)// Is this complete?
System.out.println(exception);
System.exit(1);
System.out.println("Search choice: 1)name, 2)number");
String choice = console.readLine ();
if (choice.equals("1"))
System.out.println ("Name:");
String name = console.readLine ();
Comparator fullName = new FullNameComp();
Arrays.sort(people, fullName);
Keyword kw = new Keyword(name);
Comparator nameLookup = new NameLookup();
int foundIndex = Arrays.binarySearch(people, kw, nameLookup);
if (foundIndex >= 0)
System.out.println(people[foundIndex]);
else
System.out.println("Name: " + kw + "' not found in the phonebook");
if (choice.equals("2"))
System.out.println ("Number:");
String phoneNumber = console.readLine ();
Comparator numSort = new NumberSort();
Arrays.sort(people, numSort);
Keyword kw2 = new Keyword(phoneNumber);
Comparator numLookup = new ReverseLookup();
int foundIndex2 = Arrays.binarySearch(people, kw2, numLookup);
if (foundIndex2 >= 0)
System.out.println(people[foundIndex2]);
else
System.out.println("Number: " + kw2 + " not found in the"
+ "phonebook");
System.exit(0);
private static final int ARRAY_SIZE = 8;
Describes a Telephone book.
@author LearningJava
@version 1.0
class PhoneBook
Constructor for a phonebook.
@param name A person's full name.
@param number The phone number.
public PhoneBook(String name, String number)
fullName = name;
phoneNum = number;
Method(accessor) to get full name.
@return fullName The full name.
public String getName()
return fullName;
Method(accessor)to get the telephone number.
@return phoneNum The telephone number.
public String getNumber()
return phoneNum;
Method(mutator) to alter the fullName.
@param fullName A person's full name.
public void setFullName(String fullName)
this.fullName = fullName;
Method(mutator)to alter the phone number.
@param phoneNumber The phone number.
public void setPhoneNumber(String phoneNumber)
this.phoneNum = phoneNum;
Method to return a string.
@return The phonebook as a string.
public String toString()
return fullName + " " + phoneNum;
private String fullName;
private String phoneNum;
Describes a Keyword.
@author LearningJava
@version 1.0
class Keyword
Constructor for a Keyword.
@param key The keyword.
public Keyword(String key)
this.key = key;
Method to get keyword.
@return key The keyword.
public String getKey()
return key;
Method to return a string.
@return The key as a string.
public String toString()
return key;
private String key;
A class that implemements the Comparator interface for sorting
PhoneBook objects.
@author LearningJava
@version 1.0
class FullNameComp implements Comparator
A method that compares arguments(compareTo method of the String class)
for natural order(ascending)based on full name.
@param obj1 The first object.
@param obj2 The second object.
@return A negative integer, zero, or a positive integer as this
object is less than, equal to, or greater than the
specified object.
public int compare(Object obj1, Object obj2)
PhoneBook people1 = (PhoneBook) obj1;
PhoneBook people2 = (PhoneBook) obj2;
return people1.getName().compareTo(people2.getName());
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
class NameLookup implements Comparator
A method that compares arguments for natural order.
@param obj1 The first object.
@param obj2 The second object.
@return A negative integer, zero, or a positive integer as this
object is less than, equal to, or greater than the
specified object.
public int compare(Object obj1, Object obj2)
PhoneBook phonebook = (PhoneBook) obj1;
Keyword keyword = (Keyword) obj2;
return (phonebook.getName()).compareTo(keyword.getKey());
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
class NumberSort implements Comparator
A method that compares arguments for natural order based on phone
number.
@param obj1 The first object.
@param obj2 The second object.
@return A negative integer, zero, or a positive integer as this
object is less than, equal to, or greater than the
specified object.
public int compare(Object obj1, Object obj2)
PhoneBook people1 = (PhoneBook) obj1;
PhoneBook people2 = (PhoneBook) obj2;
return people1.getNumber().compareTo(people2.getNumber());
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
class ReverseLookup implements Comparator
A method that compares arguments for natural order.
@param obj1 The first object.
@param obj2 The second object.
@return A negative integer, zero, or a positive integer as this
object is less than, equal to, or greater than the
specified object.
public int compare(Object obj1, Object obj2)
PhoneBook phonebook = (PhoneBook) obj1;
Keyword keyword = (Keyword) obj2;
return (phonebook.getNumber()).compareTo(keyword.getKey());Looks to me like you want to be using a Vector, not an Array.
i.e, declare 'people' as a vector, and replace this code
while (more && count < people.length)
String k = in.readLine();
String v = null;
if (k != null) v = in.readLine();
if (v != null)
people[count] = new PhoneBook(k, v);
count++;
else more = false;with this
while (more)
String k = in.readLine();
String v = null;
if (k != null) v = in.readLine();
if (v != null)
people.add(new PhoneBook(k, v));
else more = false;Some of the rest of the code will need changes for casting, and the slightly different way in which vectors are used, but other than that it should work. -
Determining if element is in a certain array
Hi,
I was wondering if there is a way to determine if a String element is part of an array of Strings. In other words, I want to do something like:
String myString = "blah";
String[] stringArray = {"blah", "foo"};
if (myString is part of stringArray) {
// Do stuff here
}The reason I want to do this is because I have two large String arrays, and want to determine if a String element is in one array or the other, and do some stuff based on the result.
Is there a way to do this? If so, how? Could I use compareTo, or something like that, to determine if it is part of an array?
Thanks,
DanUse java.util.Arrays.binarySearch(stringArray, myString) if the array is sorted, or use a more high-powered collection class instead (such as a java.util.ArrayList, and the methods it provides to search within).
http://java.sun.com/j2se/1.5.0/docs/api/index.html -
HI everyone I am looking for some help on an array problem.
I am reading in a text file that is in a line by line format eg.
apple
orange
pear
etc
The problem is that I want my array to increment each line. However each time a new line is read from the text file the array postion goes back to zero. Im assuming theres something wrong with my loop. Somebody please help!!!
String line;
String[] words;
int i;
try {
BufferedReader reader = new BufferedReader(new FileReader("wordlist.txt"));
while((line = reader.readLine()) != null){
words = line.split(" ");
for(i = 0; i < words.length; i++){
Arrays.sort(words);
//System.out.println(words);
if(findWord.equals(words[i])) {
Cap = "the word was found at position " + Arrays.binarySearch(words, words[i]);
test=true;
checkString();
reader.close();
I I read in
apple orange pear
carrot cucumber tomato
then apple[0] orange[1] pear[2]
but then this resets to 0 on new line i.e
carrot[0] cucumber[1] tomato[2]Correct me if Im wrong but I think I have created the
array out side the loop.Your original code declares the array outsid of the loop, but it doesn't create it. It just allocates a reference variable that will point to the aray.
Inside the loop, where you do words = split you're creating a new array each time. (And like I said, if there's only one word on a line, you don't need to spilt.)
As for putting the next
lines word into the array on each loop pass I do not
understand how to do this. Any help would be
appreciated?
for (int ix = 0; ix < numLines; ix++) {
arrar[ix] = the line that you just read
} Of course, if you're using the standard while (line != null) for loop control, then you can just skip the for part and create an index variable that you increment inside the body of the loop. -
hi, i,m trying to such through an array for an item but so far the code i'm using is not working perfectly. i'm using the binarysearch() method in java.utils.
heres the code:-
public void search(){
h=Arrays.binarySearch(ItemName, Itemname);
System.out.println(h);
if(h<0){
JOptionPane.showMessageDialog(null, "No such item in stock!!!!.", "ERROR ALERT", JOptionPane.ERROR_MESSAGE);
purchasingmethod();
itemName is the name of the array and itemname is what i'm suching so that if whatever is stored in the variable itemname is in the array i'll get the index of the item which is positive which shows the item is in the array but the problem is its also returning negative index for some items in the array hence showing that they are not in the array and hence while infact they are how do i solve this.Convert to list.
int ix = Arrays.asList(array).indexOf(searchValue);Sort array.
Arrays.sort(array);
int ix = Arrays.binarySearch(array, searchValue);Brute force.
int ix = -1;
for (int i = 0;i < array.length;i++) {
if (array.equals(searchValue)) {
ix = i;
break;
thank you very much for the brute force code it does exactly what i wanted to do. thanks -
The Input
The input file is exactly as in WordSearch.java and in fact, you can reuse almost the entire program, especially the routines to read the word and puzzle files. In order to limit the amount of output words that are less than nine characters are not to be considered matches.
Strategy
First, provide a Position class to store a row and column as a pair, and provide a constructor, toString, and equals (hashCode would also be good to have, but is not needed). Make sure Position is an immutable type.
Next, change solvePuzzle to solveBoggle as follows:
* Routine to solve the Boggle game.
* @return a Map containing the strings as keys, and the positions used
* to form the string (as a List) as values
public Map solveBoggle( )
Map results = new HashMap( );
List path = new ArrayList( );
for( int r = 0; r < rows; r++ )
for( int c = 0; c < columns; c++ )
solve( new Position( r, c ), "", paths, results );
return results;
}Observe that solveBoggle calls the routine solve for each position in the grid. solve is recursive, and implementing it is virtually the entire assignment. After you implement solve you should have a routine that can print out, in a nice form, the Map returned by solveBoggle.
The specification for the recursive solve routine is:
* Hidden recursive routine.
* @param thisPos the current position
* @param charSequence the characters in the potential matching string thusfar
* @param path the List of positions used to form the potential matching string thusfar
* @param results the Map that contains the strings that have been found as keys
* and the positions used to form the string (as a List) as values.
private void solve( Position thisPos, String charSequence, List path, Map results )
/* Less than one page of code will do it. */
}In implementing solve you will want to do the following:
Attach the character at thisPos to charSequence.
If the resulting current string is not a prefix of any word in the dictionary, you can return.
Otherwise, you will want to update the path variable, and look for some matches.
If the current string is a word in the dictionary you want to update the map.
In any event, you want to recursively call solve with appropriate parameters, on all adjacent positions, skipping those that have already been used in the current string, and being careful not to wander off the end of the board.
Don't forget to update the path variable when you return from solve.
Copying and Cloning
As much as possible, you should avoid making copies of variables. In particular, the last two parameters to solve (the List and Map are to be the same object for each unique invocation of solveBoggole. YOU MAY NOT MOVE THEM TO BE CLASS VARIABLES. However, what this means is that when you put a String as a key and a List as a value into the Map, you will need at that point to make a copy of the List, since otherwise the Map would simply be storing lots of references to the same single list (which would be empty at the end of the program). You can use any of the List (subclasses) constructors to create a List from another List.
This is the puzzle file:
fozepdkdnqlhfejdzksccfykdxnlorwvfwavbmyqclxjrgntqhvuowgrtufhnbdt
zfqatqryeqhxxuqpdmmsksjdooncssvrznssflsjbahawxsalesvwdblsqpkimdj
zxdeiwqmwxouwgukkmfjqiwkynwizztyxxehtuvrtklqsgaduhomsmyszwbywwyv
teeozafumtmebojvwxkqliimhlmfikabpgsqizkuszztnirlibbtlkgsvuzdfbhw
iboqaaltzkmnsdycgawukeohyonfpwdxxrqxubqtnfghkhkrhintobcorpwhlzgi
tyinbyiofryqykjhswcizgwrwsajuiuphceicmzifxyfjhodfqlexhxvcxgyganp
erxhfyrnxpsgyhjdzuhyefviecgkcvbhozqvzhixyddwkpzllikrpfzuhhgmeivu
jlqiuafsdlopapbnxlfnsehaopmsxjpgufpofwglhwajlbxkmcxfighwwvrtegca
nroupwfxugifhfpwjpdsxmqthjpnrrngkdbzbgyvojcwqtuakzuilmbuyshplwwv
bzxcfxzugdszwozhnvryhushnbxyxvwyuvcbsbxbgpccfblsyeshzmpmnommjimf
fogarebxvdcbgpvguonvachqsvebgrglhplbvoaqtetzuphqdvlfzuxsrcvxvele
twfolgggmaigppyumlbmhzgzdbwyfhcagiqtqxzcxhlmxlilxjxeiddlhclolopr
yfmqemubvhputxgsjdwtjchsgsirixlifxyljvnhccbxchplnogysnsygapqaazh
azsluhszmwwofobuchuuxmsdpjtpmuyouqzoaupmqmavcdqemkajzuoqfkftefhy
xhpxbejrslouogadtcmsydienpxrwfstojrppaiioyecfhhylwskzcomtnfpuzii
izzycjiqiounxcnjaftzjjncyurtuzdebfedomvybrnavajvhewqnjsogljclmgo
tltizoicfwdbwmygrvwggrumcdopsxdliwvjmemuapxydvewsddzwznyfcozztmj
siseogaqvxozvvxnaamwcawjemkfgwqaekesrfioeznzwnnwpburdqchdmoljelp
priiyswdtmepztnovhiaakkfzyqifdxwuhetcayvmcnlwcctkkvmufrtejdlmdhi
klbonbmagzncbpxnbszwasrgbxrpayymlbbydnyjoonpfmfhgedgzwmatdsvdqio
rjnuwnfkdsbjegqlnvrmrgonlgiryqfqbumzkslnknwrvmckjvwddnqpvagutnkw
kwwuqhjbwguuuyegtdjzsbqnbyhwnttxsrtiadlxlfthdxnzcwauxqiborzbnubf
lupmzblkieumdhnigncdfmgtgiwtcxaoupctqngbtanyhcinrntwzbphjnconceh
ugckvinqiaqsezhvmcrneivpyxdlcjswpuimfwcpythfuragtutzeqrcqupsgjqv
gyilwmavhkabbchuwdudtlhlhxdngtlmuvxqhanrkpslscfqfbtaodmyarlinyvh
tuzdupugeorwqzpvakyrnkpnbcwobtxwnzbkoxqsmkrcjgalqyceittlwrczkzxa
yzmmwehioynzenlwlpatjwghnigaidcieoxdueljeakknvgyljtwhaduklwuqydv
ocylglummewbceapnvnuxqridpctqhoejorrcldqsbrwgtnvraqoqjytydookdvw
tmnxatnuuhsacfwtfokvzkqxpeoajlyfxlczgstbbnddszzxpluoxkmnrcpcnnhm
ammhehifvlknnjlcwfrusfhljwnwjxiljwspeaubogobqbfojyiddpqondkycvkn
recxfyyvfpyxqdlbcwehnuwbaibcdlqxquuxttuyisxyxicbggludjvfrwjxkbuc
wobrhvprposmyuqfcbzhkumdswaezwivljmugdmxrekqycxadwipswsmsvrsrzpc
lexrhlpbpbtpfqpimzxgwrsqmjkelciyghrpsiqhjlwqboyppxxnrqgdbsjousmc
besumkdywaozqprfmovfgbjituwqolsqpmkbxnzvpquffnnteizklkueetutepjv
bvwykytaqqhvfwojgnurxqyejuxpjiklfjlpjhrzzbuexkqeamvzctdoocdzmqmr
bajkjajibfozpefrqcrvywjobonngafhcorlqcvshjtzqaqicjdagmohdewjgbti
rkvknqewbxvrzoabxdefsuoxalggmzqgmlsbbwxfvvwulyxicbqwyetypbhedxmp
jeqmaprvmqrxooissyoqchqslxyovkdgovuomolzecyssglmgbejjvduubiplnxb
kspwicxmgyeyernltrwembahckypxyqhshfalfmrdsrhmeuhwslkvltzxuouugdm
pkoapcrsulcipypntcaoptompcijlnxaylbnnuikfksxkkmdmmseigqzkbjvogym
sbchvkrdwkcgwokkdconkhmuixswgqlarphobztxlvdjmptptiedrsazquxykkyd
zhtainzvkfewuynqirvzkvacpzcbkagljcmsrnpbsuypulfefafpyhtpgvtqxbcg
dqaudswyownkjsoouvfscykkvdbsefbkxdgcveajantkhjacegwiggtclwusdxcc
bkeyphirwddepegvkeeslzuyxrqcouerfkquranofruuvaqhgwzrxuquniwbdcti
mjeglrwqiqlfsdoyzoswkksxsoyvqtfeejkpdiinyvtsyhtxxlvhvngpdhlvaqbh
coyhwguxbppbzkawvvgskmipvtmylofpcfwymtxpiprhzrgvpopbaxrysdwgrdvv
iuwwntmviffiwlfnzwpbugbolxwfaualoyhdsvycafmzsrmtqbxkjyavyxcarclh
btkvokxrskqkdcgtgdfpbimbfocytnhwitrzdqqvagigkobqthiwrwywlawgnfcy
yvxdlnbmvjufzvyseiovemtrorxewbcwwzaiobwjmsolnoduwtpdglwucuybxcxu
bzepaaamspxhfcdewthegdaizblxdlthkzwlbxzvoxcvbgzxbgdhmerlhfkkqfra
eqnfpnadmfynlynogqxswqgdvsqlyhocxbkmokrapsqcsdsyvptugzzdtpprxfww
gglxsezkwpoouhpqyikgjjkebbwyguwoajluolekcvbxeqpcabllmxpnynnghkuj
tgejtkwvfxujpjmrkzexwtkujycqkwafcgpxqlvwkpfzztsjswgqrtmatotdltkp
bznrminyxvxyopijnqzfjmfcayhntsdutsoicdgzygapxiylazqknxooyybrsgol
yevahecgkcvjmvumwmykkpyinbbfkrsivqlfupletinffktbwslijlswpwdzpxjn
nwshlfnepdlupfxlzjwiwognkloaianywhhkmvobaaxphucgfyqcnwrzhgbrgqpe
xxolufmuhjjoelwlmmnbiharneivwyzuvqfrvulcfwsjjovvakwktzbidjdbjfvg
vdxszkwegoqqenlexkqtjrbocfpmmnujssbrezvlnlbryoxyanrjguzibrwnetyy
nbprakcpyfgywfwwupiakjllajbgczerbtjbgnrgtzerhdnbuxeehrshatqfuuwv
qhzwvqeorihanueiuimbzgkbbagwxfrnmqjhinxcxeclbgtvqhyrqitrlbnigfvv
xgeivcmuiohlxagpkgharcrcdhmmojhlrlvophiyyqjvssmeatervyvbfhntswgj
jcxzlizjykgsetxfmbykbulibyduwkffodgzlhjlupdakahxeghfasqdstzodfvt
kctxleifvnggonfutobvgrzalyoqfjkrnfozlyegmmocctwvhztprspesfuargrg
lgfwemfsatucpsywurollfrflnfeuxkhfsgleleegahvvhupakanptsagaeaxrke
the dictionary file is too big to post but it is something like this:
a
aah
aardvark
aardvarks
aardwolf
aardwolves
aba
abaca
abaci
aback
abacterial
abacus
abacuses
abaft
abalone
abalones
abandon
abandoned
abandoning
abandonment
abandons
abase
abased
abasement
abasements
abases
abash
abashed
abashes
abashing
abashment
abashments
abasing
abatable
abate
abated
abatement
abater
abaters
abates
abating
abatis
abatises
abattoir
abattoirs
abaxial
abbacies
abbacy
abbe
abbess
abbey
abbot
abbots
abbreviate
abbreviated
abbreviates
abbreviating
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// WordSearch class interface: solve word search puzzle
// CONSTRUCTION: with no initializer
// ******************PUBLIC OPERATIONS******************
// int solvePuzzle( ) --> Print all words found in the
// puzzle; return number of matches
public class WordSearch
* Constructor for WordSearch class.
* Prompts for and reads puzzle and dictionary files.
public WordSearch( ) throws IOException
puzzleStream = openFile( "Enter puzzle file" );
wordStream = openFile( "Enter dictionary name" );
System.out.println( "Reading files..." );
readPuzzle( );
readWords( );
* Routine to solve the word search puzzle.
* Performs checks in all eight directions.
* @return number of matches
public int solvePuzzle( )
int matches = 0;
for( int r = 0; r < rows; r++ )
for( int c = 0; c < columns; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
return matches;
* Search the grid from a starting point and direction.
* @return number of matches
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta )
String charSequence = "";
int numMatches = 0;
int searchResult;
charSequence += theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < rows && j < columns;
i += rowDelta, j += colDelta )
charSequence += theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
return numMatches;
* Performs the binary search for word search.
* @param a the sorted array of strings.
* @param x the string to search for.
* @return last position examined;
* this position either matches x, or x is
* a prefix of the mismatch, or there is no
* word for which x is a prefix.
private static int prefixSearch( Object [ ] a, String x )
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
* Print a prompt and open a file.
* Retry until open is successful.
* Program exits if end of file is hit.
private BufferedReader openFile( String message )
String fileName = "";
FileReader theFile;
BufferedReader fileIn = null;
do
System.out.println( message + ": " );
try
fileName = in.readLine( );
if( fileName == null )
System.exit( 0 );
theFile = new FileReader( fileName );
fileIn = new BufferedReader( theFile );
catch( IOException e )
{ System.err.println( "Cannot open " + fileName ); }
} while( fileIn == null );
System.out.println( "Opened " + fileName );
return fileIn;
* Routine to read the grid.
* Checks to ensure that the grid is rectangular.
* Checks to make sure that capacity is not exceeded is omitted.
private void readPuzzle( ) throws IOException
String oneLine;
List puzzleLines = new ArrayList( );
if( ( oneLine = puzzleStream.readLine( ) ) == null )
throw new IOException( "No lines in puzzle file" );
columns = oneLine.length( );
puzzleLines.add( oneLine );
while( ( oneLine = puzzleStream.readLine( ) ) != null )
if( oneLine.length( ) != columns )
System.err.println( "Puzzle is not rectangular; skipping row" );
else
puzzleLines.add( oneLine );
rows = puzzleLines.size( );
theBoard = new char[ rows ][ columns ];
Iterator itr = puzzleLines.iterator( );
for( int r = 0; r < rows; r++ )
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toCharArray( );
* Routine to read the dictionary.
* Error message is printed if dictionary is not sorted.
private void readWords( ) throws IOException
List words = new ArrayList( );
String lastWord = null;
String thisWord;
while( ( thisWord = wordStream.readLine( ) ) != null )
if( lastWord != null && thisWord.compareTo( lastWord ) < 0 )
System.err.println( "Dictionary is not sorted... skipping" );
continue;
words.add( thisWord );
lastWord = thisWord;
theWords = words.toArray( );
// Cheap main
public static void main( String [ ] args )
WordSearch p = null;
try
p = new WordSearch( );
catch( IOException e )
System.out.println( "IO Error: " );
e.printStackTrace( );
return;
System.out.println( "Solving..." );
p.solvePuzzle( );
private int rows;
private int columns;
private char [ ][ ] theBoard;
private Object [ ] theWords;
private BufferedReader puzzleStream;
private BufferedReader wordStream;
private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
}Thank you in advanceOk, I'm stuck. Please somebody. It seems like I'm not moving inside the board. This is what I have done so far:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class WordSearch
* Constructor for WordSearch class.
* Prompts for and reads puzzle and dictionary files.
public WordSearch( ) throws IOException
puzzleStream = openFile( "Enter puzzle file" );
wordStream = openFile( "Enter dictionary name" );
System.out.println( "Reading files..." );
readPuzzle( );
readWords( );
* Private class Position is a class to store a row and a column
* as a pair.
private class Position
int row;
int column;
* A constructor from two integers
* @param r is the row of the position
* @param c is the column of the position
Position( int r, int c )
row = r;
column = c;
* First accessor
* @return the row as an int
public int getRow( )
return row;
* Second accessor
* @return the column as an int
public int getColumn( )
return column;
* Position objects are equal if both rows and columns are equal
* @return true if both rows and columns are equal; false otherwise
public boolean equals( Object aPosition )
int x = ( (Position) aPosition ).getRow( );
int y = ( (Position) aPosition ).getColumn( );
return ( ( row == x ) && ( column == y ) );
* Returns a String representation of Position
* @return a String with Position as ( x, x )
public String toString( )
return ( "( " + row + ", " + column + " )" );
} // end of Position
* Routine to solve the Boggle game.
* @return a Map containing the strings as keys, and the positions
* used to form the string (as a List) as values
public Map solveBoggle( )
Map results = new HashMap( );
List path = new ArrayList( );
boolean[][] marked = new boolean[rows][columns];
for( int r = 0; r < rows; r++ )
for( int c = 0; c < columns; c++ )
solve( new Position( r, c ), "", path, results, marked);
return results;
* Hidden recursive routine.
* @param thisPos the current position
* @param charSequence the characters in the potential matching string thusfar
* @param path the List of positions used to form the potential matching string thusfar
* @param results the Map that contains the strings that have been found as keys
* and the positions used to form the string (as a List) as values.
private void solve( Position thisPos, String charSequence, List path, Map results,
boolean[ ][ ] marked )
int row = thisPos.getRow( );
int col = thisPos.getColumn( );
charSequence += theBoard[ row ][ col ];
int searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
return;
if( theWords[ searchResult ].equals( charSequence ) )
path.add( thisPos );
results.put( charSequence, path );
path.clear( );
charSequence.replaceAll( charSequence, "" );
return;
if( !( (String)theWords[ searchResult ] ).startsWith( charSequence ) )
return;
else
path.add( thisPos );
marked[ thisPos.getRow( ) ][ thisPos.getColumn( ) ] = true;
if( ((row-1) >= 0) && ((col-1) >= 0) && !marked[row-1][col-1] )
marked[row-1][col-1] = true;
solve( new Position(row-1, col-1), charSequence, path, results, marked);
if( ((row-1) >= 0) && !marked[row-1][col] )
marked[row-1][col] = true;
solve( new Position(row-1, col), charSequence, path, results, marked);
if( ((row-1) >= 0) && ((col+1) < columns) && !marked[row-1][col+1] )
marked[row-1][col+1] = true;
solve( new Position(row-1, col+1), charSequence, path, results, marked);
if( ((col-1) >= 0) && !marked[row][col-1] )
marked[row][col-1] = true;
solve( new Position(row, col-1), charSequence, path, results, marked);
if( ((col+1) < columns) && !marked[row][col+1] )
marked[row][col+1] = true;
solve( new Position(row, col+1), charSequence, path, results, marked);
if( ((row+1) < rows) && ((col-1) >= 0) && !marked[row+1][col-1] )
marked[row+1][col-1] = true;
solve( new Position(row+1, col-1), charSequence, path, results, marked);
if( ((row+1) < rows) && !marked[row+1][col] )
marked[row+1][col] = true;
solve( new Position(row+1, col), charSequence, path, results, marked);
if( ((row+1) < rows) && ((col+1) < columns) && !marked[row+1][col+1] )
marked[row+1][col+1] = true;
solve( new Position(row+1, col+1), charSequence, path, results, marked);
* Performs the binary search for word search.
* @param a the sorted array of strings.
* @param x the string to search for.
* @return last position examined;
* this position either matches x, or x is
* a prefix of the mismatch, or there is no
* word for which x is a prefix.
private static int prefixSearch( Object [ ] a, String x )
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
* Print a prompt and open a file.
* Retry until open is successful.
* Program exits if end of file is hit.
private BufferedReader openFile( String message )
String fileName = "";
FileReader theFile;
BufferedReader fileIn = null;
do
System.out.println( message + ": " );
try
fileName = in.readLine( );
if( fileName == null )
System.exit( 0 );
theFile = new FileReader( fileName );
fileIn = new BufferedReader( theFile );
catch( IOException e )
{ System.err.println( "Cannot open " + fileName ); }
} while( fileIn == null );
System.out.println( "Opened " + fileName );
return fileIn;
* Routine to read the grid.
* Checks to ensure that the grid is rectangular.
* Checks to make sure that capacity is not exceeded is omitted.
private void readPuzzle( ) throws IOException
String oneLine;
List puzzleLines = new ArrayList( );
if( ( oneLine = puzzleStream.readLine( ) ) == null )
throw new IOException( "No lines in puzzle file" );
columns = oneLine.length( );
puzzleLines.add( oneLine );
while( ( oneLine = puzzleStream.readLine( ) ) != null )
if( oneLine.length( ) != columns )
System.err.println( "Puzzle is not rectangular; skipping row" );
else
puzzleLines.add( oneLine );
rows = puzzleLines.size( );
theBoard = new char[ rows ][ columns ];
Iterator itr = puzzleLines.iterator( );
for( int r = 0; r < rows; r++ )
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toCharArray( );
* Routine to read the dictionary.
* Error message is printed if dictionary is not sorted.
private void readWords( ) throws IOException
List words = new ArrayList( );
String thisWord;
while( ( thisWord = wordStream.readLine( ) ) != null )
words.add( thisWord );
theWords = words.toArray( );
Arrays.sort( theWords );
* Prints a String representation of the words found and their List of positions.
* @Prints a String with the words found and their List of positions.
public static void printMap( Map wordMap )
Iterator itr1 = wordMap.entrySet( ).iterator( );
String str = "";
while( itr1.hasNext( ) )
String aWord = (String)( (Map.Entry)itr1.next( ) ).getKey( );
str += "Found " + aWord + " at ";
Iterator itr2 = ( (List)( ( (Map.Entry)itr1.next( ) ).
getValue( ) ) ).iterator( );
while( itr2.hasNext( ) )
str += (Position)itr2.next( );
if( itr2.hasNext( ) )
str += ", ";
else
str += "\n";
System.out.println( str );
} // end of printMap
// Cheap main
public static void main( String [ ] args )
WordSearch p = null;
try
p = new WordSearch( );
catch( IOException e )
System.out.println( "IO Error: " );
e.printStackTrace( );
return;
System.out.println( "Solving..." );
Map wordMap = p.solveBoggle( );
p.printMap( wordMap );
private int rows;
private int columns;
private char [ ][ ] theBoard;
private Object [ ] theWords;
private BufferedReader puzzleStream;
private BufferedReader wordStream;
private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
}Thanks -
I have written the code to take a text file (from a command line argument) holding the information for the word find grid and also the file holding the words to be found in the grid. The whole find the two files and drop them into memory works all peachy keen but the rest of the program doesn't work for some oddball reason that I can't figure out (and the TAs are useless as usual). I dropped in print statements all over the world to see why it's not working but all I can see is that I hit the method SolvePuzzle and don't actually get any further than the print statement.
Just so you know, all of the methods in the program do work as I wrote them for another version of the same puzzle...it was just that I had to change the program to run with command line arguments instead of asking the user to input the file names. Please, can someone take a look at this monstrous mess and tell me how on earth I get the stupid thing to output correctly?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// WordFind class interface: solve word search puzzle
// CONSTRUCTION: with no initializer
// ******************PUBLIC OPERATIONS******************
// int solvePuzzle( ) --> Print all words found in the
// puzzle; return number of matches
public class WordFind
* Constructor for WordFind class.
* Prompts for and reads puzzle and dictionary files.
public WordFind(String fname, String fname2 ) throws IOException
loadPuzzle(fname, fname2);
//solvePuzzle( );
* Routine to solve the word search puzzle.
* Performs checks in all eight directions.
* @return number of matches
public int solvePuzzle( )
int matches = 0;
for( int r = 0; r < rows; r++ )
for( int c = 0; c < columns; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
System.out.println("testing to see if we get BBOOOOO.");
return matches;
* Search the grid from a starting point and direction.
* @return number of matches
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta )
System.out.println("testing to see if we get this far part 2.");
String charSequence = "";
int numMatches = 0;
int searchResult;
charSequence += theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < rows && j < columns;
i += rowDelta, j += colDelta )
charSequence += theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
return numMatches;
* Performs the binary search for word search.
* @param a the sorted array of strings.
* @param x the string to search for.
* @return last position examined;
* this position either matches x, or x is
* a prefix of the mismatch, or there is no
* word for which x is a prefix.
private static int prefixSearch( Object [ ] a, String x )
System.out.println("testing to see if we get this far part 3.");
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
private void loadPuzzle(String fname, String fname2)
String oneLine;
try {
// open file for reading
wsFile = new BufferedReader(new FileReader(fname));
// get the row and columns
oneLine = wsFile.readLine();
List puzzleLines = new ArrayList( );
if( ( oneLine = wsFile.readLine( ) ) == null )
throw new IOException( "No lines in puzzle file" );
int columns = oneLine.length( );
puzzleLines.add( oneLine );
while( ( oneLine = wsFile.readLine( ) ) != null )
// if( oneLine.length( ) != columns )
// System.err.println( "Puzzle is not rectangular; skipping row" );
// else
puzzleLines.add( oneLine );
int rows = puzzleLines.size( );
theBoard = new char[ rows ][ columns ];
Iterator itr = puzzleLines.iterator( );
for( int r = 0; r < rows; r++ )
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toCharArray( );
System.out.println(theBoard[r]);
//BufferedReader wsFile2;
//ring oneLine;
try {
// open file for reading
wsFile2 = new BufferedReader(new FileReader(fname2));
List words = new ArrayList( );
String lastWord = null;
String thisWord;
while( ( thisWord = wsFile2.readLine( ) ) != null )
// if( lastWord != null && thisWord.compareTo( lastWord ) < 0 )
// System.err.println( "Dictionary is not sorted... skipping" );
// continue;
words.add( thisWord );
lastWord = thisWord;
theWords = words.toArray( );
System.out.println(words);
catch (FileNotFoundException e)
System.out.println("File not found.");
catch (IOException e)
System.out.println("IO error.");
//solvePuzzle();
// Cheap main
public static void main( String [ ] args )
String fname = args[0];
String fname2 = args[1];
// String fname = "cahsiers.txt";
//String fname2 = "cashwords.txt";
WordFind p = null;
try{
System.out.println(args[0] + " " + args[1]);
p = new WordFind(fname, fname2);
catch (IOException e)
System.out.println("IO error.");
System.out.println( "Solving..." );
p.solvePuzzle( );
private char [][] theBoard;
private int rows, columns;
private Object [] theWords;
private int numWords;
private BufferedReader wsFile;
private BufferedReader wsFile2;
}Sample output - notice the only output are the test print statements at the moment
cashiers.txt cashwords.txt
BSERENITYNZEKYI
ZBREAMOANARHECM
BBASSWGITOOLKAY
QSCENERYTNLCYMM
TUORTIASEAUBDPA
JZIVVVYYVDXOWSE
FSSENREDLIWAMIR
FIRSEHRSPNLTLTT
CLSCUILRTLYKAES
XAOHQKFOEFYLUSR
ORBGIIWYDSAQLEM
GEYITNEFPGOROEA
EKALNGGAXRERCGJ
TEKRAMSGCAFETOY
[ANTIQUE, BASS, BOAT, BREAM, CABIN, CAFE, CAMPSITE, CRAFTS, CROQUET, DOWNTOWN, D
UCK, FISHING, GEESE, GOLF, GROCERY STORE, HIKING, HONEY, INN, JAM, JELLY, LAKE,
LODGE, MARKET, MOUNTAIN, POND, PRESERVES, RELAXATION, RESORT, RIVER, SCENERY, SE
RENITY, SPA, STREAM, TROUT, VACATION, VALLEY, VIEW, WALLEYE, WILDERNESS, ]
Solving...
testing to see if we get BBOOOOO.
Press any key to continue...
Thanks for all your help.
WulfYour problem is the duplicate declarations of rows/columns
class fields
private int rows, columns;
and in loadPuzzle()
int columns = oneLine.length( );//remove int
int rows = puzzleLines.size( );//ditto
the 'int' makes rows/columns local to loadPuzzle(), leaving the class fields rows/colums = 0
the for loops of solvePuzzle() are not executed because rows = 0
also, in loadPuzzle() you seem to have an extra readLine() at the top. This could be by design, but you will lose the first line
// get the row and columns
oneLine = wsFile.readLine();//<--------------
List puzzleLines = new ArrayList( ); -
Re: how to capture a frame from a video file and save it as a jpeg
package com.snn.multimedia;
* @(#)FrameAccess.java 1.5 01/03/13
* Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
import java.util.Date;
import java.util.Arrays;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.media.*;
import javax.media.control.FramePositioningControl;
import javax.media.control.TrackControl;
import javax.media.Format;
import javax.media.format.*;
import javax.media.util.BufferToImage;
import javax.media.util.ImageToBuffer;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.sun.image.codec.jpeg.*;
* Sample program to access individual video frames by using a
* "pass-thru" codec. The codec is inserted into the data flow
* path. As data pass through this codec, a callback is invoked
* for each frame of video data.
public class FrameAccess extends java.awt.Frame implements ControllerListener
Processor p;
Object waitSync = new Object();
boolean stateTransitionOK = true;
* Given a media locator, create a processor and use that processor
* as a player to playback the media.
* During the processor's Configured state, two "pass-thru" codecs,
* PreAccessCodec and PostAccessCodec, are set on the video track.
* These codecs are used to get access to individual video frames
* of the media.
* Much of the code is just standard code to present media in JMF.
public boolean open(MediaLocator ml)
try
p = Manager.createProcessor(ml);
catch (Exception e)
System.err.println("Failed to create a processor from the given url: "
+ e);
return false;
p.addControllerListener(this);
// Put the Processor into configured state.
p.configure();
if (!waitForState(p.Configured))
System.err.println("Failed to configure the processor.");
return false;
// So I can use it as a player.
p.setContentDescriptor(null);
// Obtain the track controls.
TrackControl tc[] = p.getTrackControls();
if (tc == null)
System.err.println("Failed to obtain track controls from the processor.");
return false;
// Search for the track control for the video track.
TrackControl videoTrack = null;
for (int i = 0; i < tc.length; i++)
if (tc.getFormat() instanceof VideoFormat)
videoTrack = tc[i];
break;
if (videoTrack == null)
System.err.println("The input media does not contain a video track.");
return false;
VideoFormat currentFormat = (VideoFormat)videoTrack.getFormat();
System.err.println("Video format: " + videoTrack.getFormat() );
videoTrack.setFormat(new VideoFormat("RGB", currentFormat.getSize(), currentFormat.getMaxDataLength(), currentFormat.getDataType(), currentFormat.getFrameRate()));
// Instantiate and set the frame access codec to the data flow path.
try
// Try to retrieve a FramePositioningControl from the player.
FramePositioningControl fpc = (FramePositioningControl) p.getControl("javax.media.control.FramePositioningControl");
if (fpc == null)
System.err.println("The player does not support FramePositioningControl.");
System.err.println("There's no reason to go on for the purpose of this demo.");
return false;
Time duration = p.getStopTime();
long totalFrames = 0;
if (duration != Duration.DURATION_UNKNOWN)
System.err.println("Movie duration: " + duration.getSeconds());
totalFrames = fpc.mapTimeToFrame(duration);
if (totalFrames != FramePositioningControl.FRAME_UNKNOWN)
System.err.println("Total # of video frames in the movies: "
+ totalFrames);
} else
System.err.println("The FramePositiongControl does not support mapTimeToFrame.");
} else
System.err.println("Movie duration: unknown");
long[] frames;
if (totalFrames > 0L)
double intervalDouble = Math.floor(totalFrames / 5.0);
long interval = new Double(intervalDouble).longValue();
frames = new long[5];
frames[0] = 1;
frames[1] = frames[0] + interval;
frames[2] = frames[1] + interval;
frames[3] = frames[2] + interval;
frames[4] = frames[3] + interval;
} else
frames = new long[1];
frames[0] = 1;
// Codec codec[] = { new PreAccessCodec(), new PostAccessCodec()};
Codec codec[] = { new OverlayCodec(frames)};
videoTrack.setCodecChain(codec);
catch (UnsupportedPlugInException e)
System.err.println("The process does not support effects.");
// Realize the processor.
p.prefetch();
if (!waitForState(p.Prefetched))
System.err.println("Failed to realize the processor.");
return false;
// Display the visual & control component if there's one.
setLayout(new BorderLayout());
Component cc;
Component vc;
if ((vc = p.getVisualComponent()) != null)
add("Center", vc);
if ((cc = p.getControlPanelComponent()) != null)
add("South", cc);
// Start the processor.
p.start();
setVisible(true);
return true;
public void addNotify()
super.addNotify();
pack();
* Block until the processor has transitioned to the given state.
* Return false if the transition failed.
boolean waitForState(int state)
synchronized (waitSync)
try
while (p.getState() != state && stateTransitionOK)
waitSync.wait();
catch (Exception e)
return stateTransitionOK;
* Controller Listener.
public void controllerUpdate(ControllerEvent evt)
if (evt instanceof ConfigureCompleteEvent
|| evt instanceof RealizeCompleteEvent
|| evt instanceof PrefetchCompleteEvent)
synchronized (waitSync)
stateTransitionOK = true;
waitSync.notifyAll();
} else
if (evt instanceof ResourceUnavailableEvent)
synchronized (waitSync)
stateTransitionOK = false;
waitSync.notifyAll();
} else
if (evt instanceof EndOfMediaEvent)
p.close();
System.exit(0);
* Main program
public static void main(String[] args)
if (args.length == 0)
prUsage();
System.exit(0);
String url = args[0];
if (url.indexOf(":") < 0)
prUsage();
System.exit(0);
MediaLocator ml;
if ((ml = new MediaLocator(url)) == null)
System.err.println("Cannot build media locator from: " + url);
System.exit(0);
FrameAccess fa = new FrameAccess();
if (!fa.open(ml))
System.exit(0);
static void prUsage()
System.err.println("Usage: java FrameAccess <url>");
* Inner class.
* A pass-through codec to access to individual frames.
public class PreAccessCodec implements Codec
* Callback to access individual video frames.
void accessFrame(Buffer frame)
// For demo, we'll just print out the frame #, time &
// data length.
long t = (long) (frame.getTimeStamp() / 10000000f);
System.err.println("Pre: frame #: " + frame.getSequenceNumber()
+ ", time: " + ((float) t) / 100f + ", len: "
+ frame.getLength());
* The code for a pass through codec.
// We'll advertize as supporting all video formats.
protected Format supportedIns[] = new Format[] {
new VideoFormat(null)
// We'll advertize as supporting all video formats.
protected Format supportedOuts[] = new Format[] {
new VideoFormat(null)
Format input = null, output = null;
public String getName()
return "Pre-Access Codec";
// No op.
public void open()
// No op.
public void close()
// No op.
public void reset()
public Format[] getSupportedInputFormats()
return supportedIns;
public Format[] getSupportedOutputFormats(Format in)
if (in == null)
return supportedOuts;
} else
// If an input format is given, we use that input format
// as the output since we are not modifying the bit stream
// at all.
Format outs[] = new Format[1];
outs[0] = in;
return outs;
public Format setInputFormat(Format format)
input = format;
return input;
public Format setOutputFormat(Format format)
output = format;
return output;
public int process(Buffer in, Buffer out)
// This is the "Callback" to access individual frames.
accessFrame(in);
// Swap the data between the input & output.
Object data = in.getData();
in.setData(out.getData());
out.setData(data);
// Copy the input attributes to the output
out.setFormat(in.getFormat());
out.setLength(in.getLength());
out.setOffset(in.getOffset());
return BUFFER_PROCESSED_OK;
public Object[] getControls()
return new Object[0];
public Object getControl(String type)
return null;
public class OverlayCodec extends PreAccessCodec
long[] myFrames;
BufferedImage work;
byte[] workData;
int width;
int height;
int dataLen;
RGBFormat supportedRGB = new RGBFormat(null, // size
Format.NOT_SPECIFIED, // maxDataLength
Format.byteArray, // dataType
Format.NOT_SPECIFIED, // frameRate
24, // bitsPerPixel
3, 2, 1, // red/green/blue masks
3, // pixelStride
Format.NOT_SPECIFIED, // lineStride
Format.FALSE, // flipped
Format.NOT_SPECIFIED); // endian
public OverlayCodec(long[] frames)
// force specific input format
supportedIns = new Format[] {
supportedRGB};
myFrames = new long[frames.length];
System.arraycopy(frames, 0, myFrames, 0, frames.length);
public String getName()
return "Capture Codec";
public Format setInputFormat(Format format)
if ((format != null) && (format instanceof RGBFormat)
&& format.matches(supportedRGB))
// set up working image if valid type
// (it should be since we insisted!)
Dimension size = ((RGBFormat) format).getSize();
width = size.width;
height = size.height;
dataLen = width * height * 3;
if ((dataLen > 0)
&& ((work == null) || (work.getWidth() != width)
|| (work.getHeight() != height)))
// working image - same 3-byte format as buffer
work = new BufferedImage(width, height,
BufferedImage.TYPE_3BYTE_BGR);
// reference to pixel data
workData = ((DataBufferByte) work.getRaster().getDataBuffer()).getData();
return format;
* Callback to access individual video frames.
void accessFrame(Buffer in)
try
if (Arrays.binarySearch(myFrames, in.getSequenceNumber()) >= 0)
BufferToImage stopBuffer = new BufferToImage((VideoFormat) in.getFormat());
Image stopImage = stopBuffer.createImage(in);
BufferedImage outImage = new BufferedImage(140, 96,
BufferedImage.TYPE_INT_RGB);
Graphics og = outImage.getGraphics();
og.drawImage(stopImage, 0, 0, 140, 96, null);
FileOutputStream fout = new FileOutputStream("image"
+ in.getSequenceNumber() + ".jpg");
writeImage(outImage, fout);
catch (Exception e)
e.printStackTrace();
public int process(Buffer in, Buffer out)
try
accessFrame(in);
BufferToImage stopBuffer = new BufferToImage((VideoFormat) in.getFormat());
Image stopImage = stopBuffer.createImage(in);
ImageToBuffer outImagebuffer = new ImageToBuffer();
out = outImagebuffer.createBuffer(stopImage, p.getRate());
// Swap the data between the input & output.
in.copy(out, true);
catch (Exception e)
e.printStackTrace();
return BUFFER_PROCESSED_OK;
void writeImage(BufferedImage outImage, OutputStream os) throws Exception
Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
writer.write(outImage);
ios.close();Hi,
I have a jpeg movie file 60 mins long and a text file tell me five time-lines for breaking the movie. For example, break the movie at 10:21, 16:05�
The final output should be five small jpeg movie files. Each file contains a 90 sec (30 sec before the break time and 60 sec after the break time).
Do you know any java library (jar) contain the library that can help me on programming this? Any existing source code? Any SDK for a movie editor can do that?
Please help.
Thanks
Kenny -
How do I find characters in a file?
Hi people who knows (a lot) more about Java than I do... :)
I have an array (intChars) containing integers written from a text file.
Now I would like to create a new array with all the positions in intChars where the character '{' happens to be.
I've tried something like this, but that doesn't seem to work. :(
int posTuborgBegin = Arrays.binarySearch(intChars, (int)'{' ); What is a better way to find all the positions where a given character is in a file?
Please, don't give me an answer that a newbie can't understand. Thanks.
Regards,
StefanMaybe something like that, yes. But I don't
understand it fully.
I might need to take a brake...Have a look at this demo:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) throws IOException {
System.out.println(charIndexes("Main.java", '{'));
static List<Integer> charIndexes(String fileName, char ch) throws IOException {
int offSet = 0;
List<Integer> positions = new ArrayList<Integer>();
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNextLine()) {
String line = scan.nextLine();
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i) == ch) {
positions.add(offSet+i);
offSet += line.length();
scan.close();
return positions;
}As you can see it uses a dynamic list (an ArrayList) to store the indexes of the occurrences of a specific character.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html
Edit:
Note that when you are reading your textfile as bytes you will receive different indexes since the EOL bytes will also get counted. -
I think I have got it! (Almost)...Please take a look.
Hi - I am working on a homework assignment for my Java Programming class and I have already gotten some really good advice here. I am trying to create a program that allows me to Encode/Decode Morse Code and display the cipher text or plain text depending.
I have created one base class MorseCode and have two derived classes EncodeApp and DecodeApp to illustrate the core functionality of the MorseCode class.
I have used a variety of methods. Some directly from my own twisted little mind and others after receiving excellent instruction from some of you in this forum. (thanks)
Essentially, I now have a couple of problems that I am having trouble solving.
1. I cannot figure out how to test for the entry of invalid characters in the morse code part. I mean I do not know how to account for "." and "-" as opposed to looking for valid input with Character.isLetterOrDigit() or isWhiteSpace(). Help!
2. I recieved some help earlier and did my research on HashMaps...of course this was very enlightening. So I basically followed the guidelines given by the instructions I received. But since I am an ethical person, and this is for school, I did not copy the code I received earlier. Now of course I have a bug. Essentially, when I use the Decode() method with the following input:
...<1 Space>---<1 Space>...<3 Spaces>...<1 Space>---<1 Space>... (where <Space> means hitting the spacebar on my keyboard) I should get output of SOS SOS but instead I get SOS SSOS...Why?
I have included the code below:
MorseCode.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Arrays.*;
import java.lang.Character.*;
public class MorseCode extends Object
//A-Z as elements of char array
public static char arrayAlpha[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'};
//A-Z in Morse Code Strings (0-25 indexes in alphabetical order)
public static String arrayAlphaMorse [] = {".-", "-...","-.-.","-..",".",
//0-9 as elements of char array
public static char arrayNumb[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
//0-9 in Morse Code Strings (0-9 indexes in numberical order beginning at 0)
public static String arrayNumbMorse [] = {"-----", ".----", "..---", "...--", "....-",
//All of the characters and numbers with corresponding MC as a hashmap
public static HashMap cipherKey = new HashMap();
//String to hold output
private String output = "";
public void Encode ( String s )
char messageArray[];
String messageIn = "";
messageIn = s;
messageArray = messageIn.toCharArray();
for( int i = 0; i < messageArray.length; i++)
if(Character.isLetter(messageArray))
output += arrayAlphaMorse[Arrays.binarySearch(arrayAlpha, messageArray[i])] + " ";
} else
if(Character.isDigit(messageArray[i]))
output += arrayNumbMorse[Arrays.binarySearch(arrayNumb, messageArray[i])] + " ";
} else
if(Character.isWhitespace(messageArray[i]))
output += " ";
} else
if(!(Character.isLetterOrDigit(messageArray[i])) && !(Character.isWhitespace(messageArray[i])))
JOptionPane.showMessageDialog (null, "Unsupported Characters Entered. You may only use letters, numbers and spaces.","Message as Morse Code - System Message", JOptionPane.ERROR_MESSAGE );
}//EndForLoop
}//EOEncode
public void Decode ( String s )
cipherKey.put( ".-", "A" );
cipherKey.put( "-...", "B" );
cipherKey.put( "-.-.", "C" );
cipherKey.put( "-..", "D" );
cipherKey.put( ".", "E" );
cipherKey.put( "..-.", "F" );
cipherKey.put( "--.", "G" );
cipherKey.put( "....", "H" );
cipherKey.put( "..", "I" );
cipherKey.put( ".---", "J" );
cipherKey.put( "-.-", "K" );
cipherKey.put( ".-..", "L" );
cipherKey.put( "--", "M" );
cipherKey.put( "-.", "N" );
cipherKey.put( "---", "O" );
cipherKey.put( ".--.", "P" );
cipherKey.put( "--.-", "Q" );
cipherKey.put( ".-.", "R" );
cipherKey.put( "...", "S" );
cipherKey.put( "-", "T" );
cipherKey.put( "..-", "U" );
cipherKey.put( "...-", "V" );
cipherKey.put( ".--", "W" );
cipherKey.put( "-..-", "X" );
cipherKey.put( "-.--", "Y" );
cipherKey.put( "--..", "Z" );
cipherKey.put( "-----", "0" );
cipherKey.put( ".----", "1" );
cipherKey.put( "..---", "2" );
cipherKey.put( "...--", "3" );
cipherKey.put( "....-", "4" );
cipherKey.put( ".....", "5" );
cipherKey.put( "-....", "6" );
cipherKey.put( "--...", "7" );
cipherKey.put( "---..", "8" );
cipherKey.put( "----.", "9" );
String input ="";
String intermsg = "";
String alphaString = "";
String morseString = "";
String delimiter = "#";
input = s;
StringBuffer buffer = new StringBuffer(input);
Problem is that char cannot be dereferenced??? Need to fix.
for( int i = 0; i < buffer.length()- 1; i++)
if((!(buffer.charAt(i).equals("."))) ||(!(buffer.charAt(i).equals("-"))))
JOptionPane.showMessageDialog (null, "Unsupported Characters Entered. You may only use letters, numbers and spaces.","Morse Code as Text - System Message", JOptionPane.ERROR_MESSAGE);
System.exit(0);
for( int i = 0; i < buffer.length()- 1; i++)
if((Character.isWhitespace(buffer.charAt(i))) && (Character.isWhitespace(buffer.charAt(i + 1))))
buffer.setCharAt(i + 1, '#');
intermsg = buffer.toString();
StringTokenizer tokens = new StringTokenizer( intermsg );
int length = tokens.countTokens();
StringBuffer Output = new StringBuffer((length * 2));
while(tokens.hasMoreTokens())
morseString = tokens.nextToken();
if(morseString.equals(delimiter))
Output.append(" ");
} else
alphaString = (String)cipherKey.get( morseString );
Output.append( alphaString != null ? alphaString : delimiter );
output = Output.toString();
}//EODecode
public String Output()
return output;
}//EOF
EncodeApp.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class EncodeApp extends MorseCode
public static void main(String args[] )
String input ="";
String intermsg = "";
String messageIn = "";
input = JOptionPane.showInputDialog(
"Enter Message to be Converted to Morse Code:");
intermsg = input.trim();
messageIn = intermsg.toUpperCase();
MorseCode e = new MorseCode();
e.Encode(messageIn);
JOptionPane.showMessageDialog (null, e.Output(),
"Message as Morse Code", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}//EOF
DecodeApp.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DecodeApp extends MorseCode
public static void main(String args[] )
String input = "";
String messageout = "";
input = JOptionPane.showInputDialog(
"Enter Morse Code to be Converted to Plain Text:");
messageout = input;
MorseCode d = new MorseCode();
d.Decode(messageout);
JOptionPane.showMessageDialog (null, d.Output(),
"Morse Code as Plain Text", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}//EOF
Thanks for your help!Input only <ONE SPACE> after ... --- ...
code may be taking spaces as input
or hard code a stream of " " to = a space in output -
Problem in refreshing the combo box on selection of an item in another comb
I have a situation where values to be displayed in 2nd combo box depends on the selection of an item from the 1st combo box.
Problem observed:
The 2nd combo box is not getting refreshed if the selected item from the 1st combo box has mapping to more than 10 items.
for ex:
A - AA, AB, AC, AD, AE, AF
B - BA, BB, BC, BD, BE, BF, BG, BH, BI, BJ, BK, BL, BM, BN, BO, BP
C - CA, CB, CC
D - DA, DB, DC, DD
1st combo box list:
A
B
C
D
2nd combo box list:
If the value selected from the first combo box is A, C, or D then 2nd combo box refreshes with repective values. But when the value selected is B, then 2nd combo box is not getting refreshed with respective values.
Combo Model for 1st combo box:
public class proCLMLossTypeComboModel implements javax.swing.ComboBoxModel
package nz.co.towerinsurance.quantum.claims.pro;
import javax.swing.*;
import java.util.*;
import CoreProduct.mbsoPRDLossCauseTypeList;
import javax.swing.event.*;
public class proCLMLossTypeComboModel implements javax.swing.ComboBoxModel
Vector vector = null;
mbsoPRDLossCauseTypeList mbsoPRDLossCauseTypeListInst0 = null;
public void setData(Vector vector)
this.vector = vector;
public int getSize()
if(vector != null)
return this.vector.size();
else
return 0;
public void addListDataListener(ListDataListener l)
public void removeListDataListener(ListDataListener l)
public Object getElementAt(int index)
return this.vector.elementAt(index);
public Object getSelectedItem()
return this.mbsoPRDLossCauseTypeListInst0;
public void setSelectedItem(Object anItem)
mbsoPRDLossCauseTypeList mbsoPRDLossCauseTypeListInst1 = (mbsoPRDLossCauseTypeList)anItem;
this.mbsoPRDLossCauseTypeListInst0 = mbsoPRDLossCauseTypeListInst1;
public Vector getData()
return this.vector;
Combo Model for 2nd combo box:
package nz.co.towerinsurance.quantum.claims.pro;
import javax.swing.*;
import java.util.*;
import CoreProduct.mbsoPRDCauseTypeList;
import javax.swing.event.*;
public class proCLMCauseTypeComboModel implements javax.swing.ComboBoxModel
Vector vector = null;
mbsoPRDCauseTypeList mbsoPRDCauseTypeListInst0 = null;
public void setData(Vector vector)
this.vector = vector;
public int getSize()
if(vector != null)
return this.vector.size();
else
return 0;
public void addListDataListener(ListDataListener l)
public void removeListDataListener(ListDataListener l)
public Object getElementAt(int index)
return this.vector.elementAt(index);
public Object getSelectedItem()
return this.mbsoPRDCauseTypeListInst0;
public void setSelectedItem(Object anItem)
mbsoPRDCauseTypeList mbsoPRDCauseTypeListInst1 = (mbsoPRDCauseTypeList)anItem;
this.mbsoPRDCauseTypeListInst0 = mbsoPRDCauseTypeListInst1;
public Vector getData()
return this.vector;
The Panel inside which these combo boxes are used:
package nz.co.towerinsurance.quantum.claims.pro;
import nz.co.towerinsurance.quantum.logger.MessageLogger;
import nz.co.towerinsurance.quantum.claims.vmo.*;
import nz.co.towerinsurance.quantum.utility.uhoUTLDialogueContext;
import nz.co.towerinsurance.quantum.utility.uhoUTLModelHolder;
import nz.co.towerinsurance.quantum.utility.uhoUTLInteraction;
import nz.co.towerinsurance.quantum.utility.uhoUTLNotesContext;
import nz.co.towerinsurance.quantum.utility.uhoUTLPrivacyContext;
import nz.co.towerinsurance.quantum.utility.uhoUTLProcessImpContext;
import nz.co.towerinsurance.quantum.help.*;
import nz.co.towerinsurance.quantum.document.*;
import nz.co.towerinsurance.quantum.task.*;
import nz.co.towerinsurance.quantum.qtm.*;
import nz.co.towerinsurance.quantum.claims.uhoCLMClientModel;
import nz.co.towerinsurance.quantum.claims.utility.*;
import MCType.*;
import Claim.*;
import Client.*;
import Policy.*;
import CoreProduct.*;
import Security.*;
import MCUtil.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.ButtonGroup.*;
import java.text.*;
public class proSummaryPanel extends proCLMPanelBase implements proCLMRefreshInterface, proCLMDeclineReasonInterface
private static final MessageLogger msgLogger=MessageLogger.getLogger("claims.pro.proSummaryPanel");
uhoCLMClientModel uhoCLMClientModelInst0 = null;
Vector VectorInst0 = new Vector();
JRadioButton jRdBtnSummaryPM = new JRadioButton();
JRadioButton jRdBtnSummaryAM = new JRadioButton();
ButtonGroup ButtonGroupInst0 = new ButtonGroup();
JButton jBtnSummarySearch = new JButton();
JLabel jLblSummaryCompanyName = new JLabel();
JLabel jLblSummaryCauseType = new JLabel();
JTextField jTxtFldSummaryAmountSaved = new JTextField();
JTextField jTxtFldSummaryDateNotified = new JTextField();
JTextField jTxtFldSummary = new JTextField();
JTextField jTxtFldSummarySuburb = new JTextField();
JLabel jLblSummaryCatCode = new JLabel();
JLabel jLblSummaryLossDesc = new JLabel();
JLabel jLblSummaryDateNotified = new JLabel();
JLabel jLblSummaryCity = new JLabel();
JLabel jLblSummaryTime = new JLabel();
JLabel jLblSummaryDeclineReason = new JLabel();
JCheckBox jChkBxNcbLost = new JCheckBox();
JCheckBox jChkBxLegal = new JCheckBox();
JCheckBox jChkBxNoBlameBonus = new JCheckBox();
JLabel jLblSummaryPostCode = new JLabel();
JTextField jTxtFldSummaryStreetName = new JTextField();
JTextField jTxtFldSummaryLossDate = new JTextField();
JTextField jTxtFldSummaryCity = new JTextField();
JTextField jTxtFldSummaryTime = new JTextField();
JLabel jLblSummaryLossType = new JLabel();
JTextField jTxtFldSummaryPhone = new JTextField();
JTextField jTxtFldSummaryCompanyName = new JTextField();
JLabel jLblSummarySuburb = new JLabel();
JTextArea jTxtArLossDescription = new JTextArea();
JScrollPane jScrPnSummaryLossDesc = new JScrollPane(jTxtArLossDescription);
JTextField jTxtFldSummaryDeclineReason = new JTextField();
JPanel jPanel2 = new JPanel();
JPanel jPanel1 = this;
JLabel jLblSummaryPhone = new JLabel();
JTextField jTxtFldSummaryPostCode = new JTextField();
JLabel jLblSummaryAmountSaved = new JLabel();
JPanel jPnlSummaryCoy = new JPanel();
JLabel jLblSummaryStreetName = new JLabel();
Vector lossTypeVec = new Vector();
JComboBox jCmbBxSummaryLossType = new JComboBox(lossTypeVec);
proCLMLossTypeComboModel lossTypeComboModel = new proCLMLossTypeComboModel();
Vector causeTypeVec = new Vector();
JComboBox jCmbBxSummaryCauseType = new JComboBox();
proCLMCauseTypeComboModel causeTypeComboModel = new proCLMCauseTypeComboModel();
Vector CatCodeVec = new Vector();
JComboBox jCmbBxSummaryCatCode = new JComboBox();
proCLMCatCodeComboModel catCodeComboModel = new proCLMCatCodeComboModel();
JLabel jLblSummaryLossDate = new JLabel();
JButton jBtnSave = new JButton();
JButton jBtnCancel = new JButton();
Border border1;
TitledBorder titledBorder1;
Border border2;
Border border3;
TitledBorder titledBorder2;
Border border4;
TitledBorder titledBorder3;
GridBagLayout gridBagLayout1 = new GridBagLayout();
GridBagLayout gridBagLayout2 = new GridBagLayout();
Border border5;
TitledBorder titledBorder4;
GridBagLayout gridBagLayout3 = new GridBagLayout();
GridBagLayout gridBagLayout4 = new GridBagLayout();
Component component1;
Component component2;
* @parameter uhoUTLInteraction ,mbsoSEMPrivilege
* @return
public proSummaryPanel(proQTMBase parent, uhoUTLInteraction inter,mbsoSEMPrivilege services)
super(parent,inter,services);
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
* Component initialization
* @parameter
* @return void
private void jbInit() throws Exception
component1 = Box.createHorizontalStrut(8);
component2 = Box.createHorizontalStrut(8);
jCmbBxSummaryLossType.setMinimumSize(new Dimension(225, 25));
// set the combo models
jCmbBxSummaryLossType.setModel(lossTypeComboModel);
jCmbBxSummaryCauseType.setModel(causeTypeComboModel);
jCmbBxSummaryCatCode.setModel(catCodeComboModel);
// renderer for the loss type combo
jCmbBxSummaryLossType.setRenderer(new DefaultListCellRenderer()
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
mbsoPRDLossCauseTypeList mbsoPRDLossTypeListObj = (mbsoPRDLossCauseTypeList) value;
String v = (mbsoPRDLossTypeListObj == null) ? null:mbsoPRDLossTypeListObj.GetLossTypeName().toString();
return super.getListCellRendererComponent(list,v,index,isSelected,cellHasFocus);
// key selection manager for loss type combo
jCmbBxSummaryLossType.setKeySelectionManager(new javax.swing.JComboBox.KeySelectionManager()
public int selectionForKey(char aKey,ComboBoxModel aModel)
try
Vector vector = lossTypeComboModel.getData();
// prepare a character array witht the first letter of loss types in lower case
char[] characterArray = new char[vector.size()];
for(int i=0;i<vector.size();i++)
mbsoPRDLossCauseTypeList mbsoPRDLossCauseTypeListInst0 = (mbsoPRDLossCauseTypeList)vector.elementAt(i);
char charac = mbsoPRDLossCauseTypeListInst0.GetLossTypeName().toString().toLowerCase().charAt(0);
characterArray[i] = charac;
Character char1 = new Character(aKey);
int index = 0;
if(char1.isUpperCase(aKey))
char char2 = char1.toLowerCase(aKey);
index = java.util.Arrays.binarySearch(characterArray,char2);
else
index = java.util.Arrays.binarySearch(characterArray,aKey);
if(index > 0)
jCmbBxSummaryLossType.setSelectedIndex(index);
else
jCmbBxSummaryLossType.setSelectedIndex(0);
jCmbBxSummaryLossType.repaint();
if(index > 0)
return index;
else
return 0;
catch(Exception e1)
msgLogger.fatal("Exception : proSumamryPanel : loss type combo key sel mgr : "+e1.getMessage());
return 0;
// renderer for cause type combo
jCmbBxSummaryCauseType.setRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
mbsoPRDCauseTypeList mbsoPRDCauseTypeListObj = (mbsoPRDCauseTypeList) value;
String v = (mbsoPRDCauseTypeListObj == null) ? null:mbsoPRDCauseTypeListObj.GetCauseTypeName().toString();
return super.getListCellRendererComponent(list,v,index,isSelected,cellHasFocus);
// key selection manager for loss type combo
jCmbBxSummaryCauseType.setKeySelectionManager(new javax.swing.JComboBox.KeySelectionManager()
public int selectionForKey(char aKey,ComboBoxModel aModel)
try
Vector vector = causeTypeComboModel.getData();
// prepare a character array witht the first letter of loss types in lower case
char[] characterArray = new char[vector.size()];
for(int i=0;i<vector.size();i++)
mbsoPRDCauseTypeList mbsoPRDCauseTypeListInst0 = (mbsoPRDCauseTypeList)vector.elementAt(i);
char charac = mbsoPRDCauseTypeListInst0.GetCauseTypeName().toString().toLowerCase().charAt(0);
characterArray[i] = charac;
Character char1 = new Character(aKey);
int index = 0;
if(char1.isUpperCase(aKey))
char char2 = char1.toLowerCase(aKey);
index = java.util.Arrays.binarySearch(characterArray,char2);
else
index = java.util.Arrays.binarySearch(characterArray,aKey);
if(index > 0)
jCmbBxSummaryCauseType.setSelectedIndex(index);
else
jCmbBxSummaryCauseType.setSelectedIndex(0);
jCmbBxSummaryCauseType.repaint();
if(index > 0)
return index;
else
return 0;
catch(Exception e1)
msgLogger.fatal("Exception : proSumamryPanel : cause type combo key sel mgr : "+e1.getMessage());
return 0;
jBtnSummarySearch.setBorder(BorderFactory.createRaisedBevelBorder());
jBtnSummarySearch.setMaximumSize(new Dimension(119, 23));
jBtnSummarySearch.setPreferredSize(new Dimension(65, 23));
jBtnSummarySearch.setMnemonic(KeyEvent.VK_E); // 20/12
jBtnSummarySearch.setText("Search");
this.setLayout(gridBagLayout4);
ButtonGroupInst0.add(jRdBtnSummaryPM);
ButtonGroupInst0.add(jRdBtnSummaryAM);
border1 = BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142));
titledBorder1 = new TitledBorder(border1,"Where Is It Now?");
border2 = BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142));
border3 = BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142));
titledBorder2 = new TitledBorder(border3,"Where Is It Now?");
border4 = BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142));
titledBorder3 = new TitledBorder(border4,"Summary");
border5 = BorderFactory.createEtchedBorder(Color.white,new Color(142, 142, 142));
titledBorder4 = new TitledBorder(border5,"Location of Vehicle/Boat");
jScrPnSummaryLossDesc.setToolTipText("");
jScrPnSummaryLossDesc.setFont(new java.awt.Font("SansSerif", 0, 12));
jScrPnSummaryLossDesc.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jLblSummarySuburb.setText("Suburb");
jLblSummarySuburb.setForeground(Color.black);
jLblSummarySuburb.setPreferredSize(new Dimension(100, 17));
jLblSummarySuburb.setFont(new java.awt.Font("SansSerif", 1, 12));
jTxtFldSummaryCompanyName.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryCompanyName.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryCompanyName.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryCompanyName.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryPhone.setToolTipText("");
jTxtFldSummaryPhone.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryPhone.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryPhone.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryPhone.setFont(new java.awt.Font("SansSerif", 0, 12));
jLblSummaryLossType.setText("Loss Type");
jLblSummaryLossType.setForeground(Color.black);
jLblSummaryLossType.setPreferredSize(new Dimension(102, 17));
jLblSummaryLossType.setFont(new java.awt.Font("SansSerif", 1, 12));
jTxtFldSummaryTime.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryTime.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryTime.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryTime.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryCity.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryCity.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryCity.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryCity.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryLossDate.setBackground(Color.cyan);
jTxtFldSummaryLossDate.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryLossDate.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryLossDate.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryLossDate.setFont(new java.awt.Font("SansSerif", 0, 12));
jBtnSave.setToolTipText("");
jBtnSave.setBorder(BorderFactory.createRaisedBevelBorder());
jBtnSave.setMnemonic('S');
jBtnSave.setText("Save");
jBtnSave.setPreferredSize(new Dimension(100,23)); // 30/07
jBtnSummarySearch.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent e) {
jBtnSummarySearch_actionPerformed(e);
//the listener for losstype combobox
jCmbBxSummaryLossType.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
jCmbBxSummaryLossType_itemStateChanged(e);
//Actioin listener for Save button
jBtnSave.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(ActionEvent e)
jBtnSave_actionPerformed(e);
//Actioin listener for Cancel button
jTxtFldSummaryStreetName.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryStreetName.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryStreetName.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryStreetName.setPreferredSize(new Dimension(100, 20));
jLblSummaryPostCode.setText("Post Code");
jLblSummaryPostCode.setForeground(Color.black);
jLblSummaryPostCode.setPreferredSize(new Dimension(100, 17));
jLblSummaryPostCode.setFont(new java.awt.Font("SansSerif", 1, 12));
jChkBxNcbLost.setFont(new java.awt.Font("SansSerif", 1, 12));
jChkBxNcbLost.setPreferredSize(new Dimension(130, 17));
jChkBxNcbLost.setText("NCB Lost");
jLblSummaryDeclineReason.setText("Decline Reason");
jLblSummaryDeclineReason.setForeground(Color.black);
jLblSummaryDeclineReason.setPreferredSize(new Dimension(102, 17));
jLblSummaryDeclineReason.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryTime.setText("Time");
jLblSummaryTime.setForeground(Color.black);
jLblSummaryTime.setPreferredSize(new Dimension(35, 17));
jLblSummaryTime.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryCity.setText("Town/City");
jLblSummaryCity.setForeground(Color.black);
jLblSummaryCity.setPreferredSize(new Dimension(100, 17));
jLblSummaryCity.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryDateNotified.setText("Date Notified");
jLblSummaryDateNotified.setForeground(Color.black);
jLblSummaryDateNotified.setPreferredSize(new Dimension(102, 17));
jLblSummaryDateNotified.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryLossDesc.setText("Loss Description");
jLblSummaryLossDesc.setForeground(Color.black);
jLblSummaryLossDesc.setPreferredSize(new Dimension(102, 17));
jLblSummaryLossDesc.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryCatCode.setText("Catastrophe Code");
jLblSummaryCatCode.setForeground(Color.black);
jLblSummaryCatCode.setFont(new java.awt.Font("SansSerif", 1, 12));
jTxtFldSummarySuburb.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummarySuburb.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummarySuburb.setMinimumSize(new Dimension(100, 20));
jTxtFldSummarySuburb.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryAmountSaved.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryAmountSaved.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryAmountSaved.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryAmountSaved.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryDateNotified.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryDateNotified.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryDateNotified.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryDateNotified.setPreferredSize(new Dimension(100, 20));
jLblSummaryCauseType.setText("Cause Type");
jLblSummaryCauseType.setForeground(Color.black);
jLblSummaryCauseType.setPreferredSize(new Dimension(102, 17));
jLblSummaryCauseType.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryCompanyName.setText("Company Name");
jLblSummaryCompanyName.setForeground(Color.black);
jLblSummaryCompanyName.setPreferredSize(new Dimension(100, 17));
jLblSummaryCompanyName.setFont(new java.awt.Font("SansSerif", 1, 12));
jCmbBxSummaryCatCode.setFont(new java.awt.Font("SansSerif", 0, 12));
jCmbBxSummaryCatCode.setMinimumSize(new Dimension(225, 25)); // on 21/11
jCmbBxSummaryCatCode.setPreferredSize(new Dimension(126, 25));
jRdBtnSummaryPM.setFont(new java.awt.Font("SansSerif", 1, 12));
jRdBtnSummaryPM.setPreferredSize(new Dimension(40, 17));
jRdBtnSummaryPM.setText("pm");
jTxtFldSummaryDeclineReason.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtFldSummaryDeclineReason.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryDeclineReason.setMinimumSize(new Dimension(225, 20));
jTxtFldSummaryDeclineReason.setPreferredSize(new Dimension(225, 20));
jChkBxLegal.setPreferredSize(new Dimension(130, 17));
jChkBxLegal.setText("Legal");
jChkBxLegal.setActionCommand("jChkBxLegal");
jChkBxLegal.setFont(new java.awt.Font("SansSerif", 1, 12));
jPanel2.setBorder(BorderFactory.createEtchedBorder());
jPanel2.setLayout(gridBagLayout1);
jPanel1.setLayout(gridBagLayout3);
jLblSummaryPhone.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryPhone.setForeground(Color.black);
jLblSummaryPhone.setPreferredSize(new Dimension(100, 17));
jLblSummaryPhone.setText("Phone");
jRdBtnSummaryAM.setPreferredSize(new Dimension(40, 17));
jRdBtnSummaryAM.setText("am");
jRdBtnSummaryAM.setFont(new java.awt.Font("SansSerif", 1, 12));
jRdBtnSummaryAM.setSelected(true); // 20/12
jTxtFldSummaryPostCode.setBorder(BorderFactory.createLoweredBevelBorder());
jTxtFldSummaryPostCode.setMinimumSize(new Dimension(100, 20));
jTxtFldSummaryPostCode.setPreferredSize(new Dimension(100, 20));
jTxtFldSummaryPostCode.setFont(new java.awt.Font("SansSerif", 0, 12));
jLblSummaryAmountSaved.setText("Amount Saved");
jLblSummaryAmountSaved.setForeground(Color.black);
jLblSummaryAmountSaved.setPreferredSize(new Dimension(102, 17));
jLblSummaryAmountSaved.setFont(new java.awt.Font("SansSerif", 1, 12));
jPnlSummaryCoy.setFont(new java.awt.Font("SansSerif", 1, 12));
jPnlSummaryCoy.setBorder(titledBorder4);
jPnlSummaryCoy.setLayout(gridBagLayout2);
jLblSummaryStreetName.setFont(new java.awt.Font("SansSerif", 1, 12));
jLblSummaryStreetName.setForeground(Color.black);
jLblSummaryStreetName.setPreferredSize(new Dimension(100, 17));
jLblSummaryStreetName.setText("Street Name");
jCmbBxSummaryLossType.setBackground(Color.cyan);
jCmbBxSummaryLossType.setFont(new java.awt.Font("SansSerif", 0, 12));
jCmbBxSummaryLossType.setPreferredSize(new Dimension(225, 26));
jCmbBxSummaryCauseType.setBackground(Color.cyan);
jCmbBxSummaryCauseType.setFont(new java.awt.Font("SansSerif", 0, 12));
jCmbBxSummaryCauseType.setPreferredSize(new Dimension(225, 26));
jLblSummaryLossDate.setText("Loss Date");
jLblSummaryLossDate.setForeground(Color.black);
jLblSummaryLossDate.setPreferredSize(new Dimension(102, 17));
jLblSummaryLossDate.setFont(new java.awt.Font("SansSerif", 1, 12));
jTxtArLossDescription.setLineWrap(true);
jTxtArLossDescription.setWrapStyleWord(true);
jTxtArLossDescription.setBackground(Color.cyan);
jTxtArLossDescription.setFont(new java.awt.Font("SansSerif", 0, 12));
jTxtArLossDescription.setBounds(new Rectangle(124, 39, 394, 46));
jChkBxNoBlameBonus.setPreferredSize(new Dimension(130, 17));
jChkBxNoBlameBonus.setText("No Blame Bonus ");
jChkBxNoBlameBonus.setFont(new java.awt.Font("SansSerif", 1, 12));
jPanel1.setBorder(titledBorder3);
jPanel1.setBounds(new Rectangle(23, 11, 810, 436));
jPanel1.add(jLblSummaryCatCode, new GridBagConstraints(0, 6, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jScrPnSummaryLossDesc, new GridBagConstraints(1, 1, 6, 1, 0.9, 0.15
,GridBagConstraints.SOUTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jScrPnSummaryLossDesc.getViewport().add(jTxtArLossDescription, null);
jPanel1.add(jRdBtnSummaryPM, new GridBagConstraints(5, 0, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jTxtFldSummaryDeclineReason, new GridBagConstraints(1, 8, 2, 1, 0.1, 0.1
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryLossDesc, new GridBagConstraints(0, 1, 1, 1, 0.1, 0.5
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryLossType, new GridBagConstraints(0, 3, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryCauseType, new GridBagConstraints(0, 4, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryDeclineReason, new GridBagConstraints(0, 8, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryLossDate, new GridBagConstraints(0, 0, 1, 1, 0.1, 0.05
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jTxtFldSummaryTime, new GridBagConstraints(3, 0, 1, 1, 0.1, 0.05
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryTime, new GridBagConstraints(3, 0, 1, 1, 0.1, 0.05
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 107, 7));
jPanel1.add(jRdBtnSummaryAM, new GridBagConstraints(4, 0, 1, 1, 0.1, 0.05
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jCmbBxSummaryCauseType, new GridBagConstraints(1, 4, 2, 1, 0.1, 0.05
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jTxtFldSummaryLossDate, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.05
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jTxtFldSummaryDateNotified, new GridBagConstraints(1, 7, 1, 1, 0.1, 0.05
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jPanel2, new GridBagConstraints(0, 9, 6, 1, 1.0, 0.1
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(jChkBxNoBlameBonus, new GridBagConstraints(3, 0, 1, 1, 0.1, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(jChkBxLegal, new GridBagConstraints(4, 0, 1, 1, 0.1, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(jBtnSave, new GridBagConstraints(5, 0, 1, 1, 0.1, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(jChkBxNcbLost, new GridBagConstraints(2, 0, 1, 1, 0.1, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(component1, new GridBagConstraints(1, 0, 1, 1, 0.35, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel2.add(component2, new GridBagConstraints(5, 0, 1, 1, 0.35, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jCmbBxSummaryLossType, new GridBagConstraints(1, 3, 2, 1, 0.1, 0.05
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jCmbBxSummaryCatCode, new GridBagConstraints(1, 6, 2, 1, 0.1, 0.05
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jPnlSummaryCoy, new GridBagConstraints(2, 3, 4, 6, 1.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummaryPhone, new GridBagConstraints(0, 6, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummarySuburb, new GridBagConstraints(0, 3, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummaryStreetName, new GridBagConstraints(1, 2, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummaryCity, new GridBagConstraints(1, 4, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummaryPostCode, new GridBagConstraints(1, 5, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummarySuburb, new GridBagConstraints(1, 3, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummaryPostCode, new GridBagConstraints(0, 5, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummaryPhone, new GridBagConstraints(1, 6, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jTxtFldSummaryCompanyName, new GridBagConstraints(1, 0, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummaryCompanyName, new GridBagConstraints(0, 0, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummaryStreetName, new GridBagConstraints(0, 2, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPnlSummaryCoy.add(jLblSummaryCity, new GridBagConstraints(0, 4, 1, 1, 0.5, 0.16
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jLblSummaryDateNotified, new GridBagConstraints(0, 7, 1, 1, 0.1, 0.05
,GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jBtnSummarySearch, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jTxtFldSummaryLossDate.grabFocus();
jTxtFldSummaryLossDate.setNextFocusableComponent(jTxtFldSummaryTime);
jTxtFldSummaryTime.setNextFocusableComponent(jRdBtnSummaryAM);
jRdBtnSummaryAM.setNextFocusableComponent(jRdBtnSummaryPM);
jRdBtnSummaryPM.setNextFocusableComponent(jTxtArLossDescription);
jTxtArLossDescription.setNextFocusableComponent(jCmbBxSummaryLossType);
jCmbBxSummaryLossType.setNextFocusableComponent(jCmbBxSummaryCauseType);
jCmbBxSummaryCauseType.setNextFocusableComponent(jBtnSummarySearch);
jBtnSummarySearch.setNextFocusableComponent(jCmbBxSummaryCatCode);
jCmbBxSummaryCatCode.setNextFocusableComponent(jTxtFldSummaryDateNotified);
jTxtFldSummaryDateNotified.setNextFocusableComponent(jTxtFldSummaryDeclineReason);
jTxtFldSummaryDeclineReason.setNextFocusableComponent(jTxtFldSummaryCompanyName);
jTxtFldSummaryCompanyName.setNextFocusableComponent(jTxtFldSummaryStreetName);
jTxtFldSummaryStreetName.setNextFocusableComponent(jTxtFldSummarySuburb);
jTxtFldSummarySuburb.setNextFocusableComponent(jTxtFldSummaryCity);
jTxtFldSummaryCity.setNextFocusableComponent(jTxtFldSummaryPostCode);
jTxtFldSummaryPostCode.setNextFocusableComponent(jTxtFldSummaryPhone);
jTxtFldSummaryPhone.setNextFocusableComponent(jChkBxNcbLost);
jChkBxNcbLost.setNextFocusableComponent(jChkBxNoBlameBonus);
jChkBxNoBlameBonus.setNextFocusableComponent(jChkBxLegal);
jChkBxLegal.setNextFocusableComponent(jBtnSave);
jBtnSave.setNextFocusabl &nbsthe very simple strategy to do is to call removeAllItems() method for the 2nd combox box and then insert the contents. this is because the validate() method is not repeatedly called and so the contents are not updated immediately.
-
Problem in near duplicate detection in c#
I have Develop application for near duplicate detection in c#.This application work for strings only but it's not working for pdf files.may be i think
GetSimilarity method can not work properly but error not be raised.
my application code like as:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using System.Threading;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Text.RegularExpressions;
using WindowsFormsApplication1.appcode;
namespace WindowsFormsApplication1
public partial class Form1 : Form
string filename;
FileInfo[] data1;
FileInfo[] data2;
string path;
public Form1()
InitializeComponent();
private void button1_Click(object sender, EventArgs e)
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
filename = Path.GetFileName(openFileDialog.FileName);
path = Path.GetDirectoryName(openFileDialog.FileName);
textBox1.Text = path + "\\" + filename;
private void button2_Click(object sender, EventArgs e)
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
filename = Path.GetFileName(openFileDialog.FileName);
path = Path.GetDirectoryName(openFileDialog.FileName);
textBox2.Text = path + "\\" + filename;
public static string ExtractTextFromPdf(string filename)
using (PdfReader r = new PdfReader(filename))
StringBuilder text = new StringBuilder();
for (int i = 1; i <= r.NumberOfPages; i++)
text.Append(PdfTextExtractor.GetTextFromPage(r, i));
string first = text.ToString();
return first;
public static string Extract(string filename)
using (PdfReader r = new PdfReader(filename))
StringBuilder text = new StringBuilder();
for (int i = 1; i <= r.NumberOfPages; i++)
text.Append(PdfTextExtractor.GetTextFromPage(r, i));
string second = text.ToString();
return second;
private void button3_Click(object sender, EventArgs e)
StopWordsHandler stopword = new StopWordsHandler();
string s = ExtractTextFromPdf(textBox1.Text);
string s1 = Extract(textBox2.Text);
string[] doc = new string[2]{s,s1 };
TFIDF tfidf = new TFIDF(doc);
float fl = tfidf.GetSimilarity(0,1);
var sformatted = string.Format("Value: {0:P2}.", fl);
StopWordsHandler.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1.appcode
class StopWordsHandler
public static string[] stopWordsList=new string[] {
"a",
"about",
"above",
"across",
"afore",
"aforesaid",
"after",
"again",
"against",
"agin",
"ago",
"aint",
"albeit",
"all",
"almost",
"alone",
"along",
"alongside",
"already",
"also",
"although",
"always",
"am",
"american",
"amid",
"amidst",
"among",
"amongst",
"an",
"and",
"anent",
"another",
"any",
"anybody",
"anyone",
"anything",
"are",
"aren't",
"around",
"as",
"aslant",
"astride",
"at",
"athwart",
"away",
"b",
"back",
"bar",
"barring",
"be",
"because",
"been",
"before",
"behind",
"being",
"below",
"beneath",
"beside",
"besides",
"best",
"better",
"between",
"betwixt",
"beyond",
"both",
"but",
"by",
"c",
"can",
"cannot",
"can't",
"certain",
"circa",
"close",
"concerning",
"considering",
"cos",
"could",
"couldn't",
"couldst",
"d",
"dare",
"dared",
"daren't",
"dares",
"daring",
"despite",
"did",
"didn't",
"different",
"directly",
"do",
"does",
"doesn't",
"doing",
"done",
"don't",
"dost",
"doth",
"down",
"during",
"durst",
"e",
"each",
"early",
"either",
"em",
"english",
"enough",
"ere",
"even",
"ever",
"every",
"everybody",
"everyone",
"everything",
"except",
"excepting",
"f",
"failing",
"far",
"few",
"first",
"five",
"following",
"for",
"four",
"from",
"g",
"gonna",
"gotta",
"h",
"had",
"hadn't",
"hard",
"has",
"hasn't",
"hast",
"hath",
"have",
"haven't",
"having",
"he",
"he'd",
"he'll",
"her",
"here",
"here's",
"hers",
"herself",
"he's",
"high",
"him",
"himself",
"his",
"home",
"how",
"howbeit",
"however",
"how's",
"i",
"id",
"if",
"ill",
"i'm",
"immediately",
"important",
"in",
"inside",
"instantly",
"into",
"is",
"isn't",
"it",
"it'll",
"it's",
"its",
"itself",
"i've",
"j",
"just",
"k",
"l",
"large",
"last",
"later",
"least",
"left",
"less",
"lest",
"let's",
"like",
"likewise",
"little",
"living",
"long",
"m",
"many",
"may",
"mayn't",
"me",
"mid",
"midst",
"might",
"mightn't",
"mine",
"minus",
"more",
"most",
"much",
"must",
"mustn't",
"my",
"myself",
"n",
"near",
"'neath",
"need",
"needed",
"needing",
"needn't",
"needs",
"neither",
"never",
"nevertheless",
"new",
"next",
"nigh",
"nigher",
"nighest",
"nisi",
"no",
"no-one",
"nobody",
"none",
"nor",
"not",
"nothing",
"notwithstanding",
"now",
"o",
"o'er",
"of",
"off",
"often",
"on",
"once",
"one",
"oneself",
"only",
"onto",
"open",
"or",
"other",
"otherwise",
"ought",
"oughtn't",
"our",
"ours",
"ourselves",
"out",
"outside",
"over",
"own",
"p",
"past",
"pending",
"per",
"perhaps",
"plus",
"possible",
"present",
"probably",
"provided",
"providing",
"public",
"q",
"qua",
"quite",
"r",
"rather",
"re",
"real",
"really",
"respecting",
"right",
"round",
"s",
"same",
"sans",
"save",
"saving",
"second",
"several",
"shall",
"shalt",
"shan't",
"she",
"shed",
"shell",
"she's",
"short",
"should",
"shouldn't",
"since",
"six",
"small",
"so",
"some",
"somebody",
"someone",
"something",
"sometimes",
"soon",
"special",
"still",
"such",
"summat",
"supposing",
"sure",
"t",
"than",
"that",
"that'd",
"that'll",
"that's",
"the",
"thee",
"their",
"theirs",
"their's",
"them",
"themselves",
"then",
"there",
"there's",
"these",
"they",
"they'd",
"they'll",
"they're",
"they've",
"thine",
"this",
"tho",
"those",
"thou",
"though",
"three",
"thro'",
"through",
"throughout",
"thru",
"thyself",
"till",
"to",
"today",
"together",
"too",
"touching",
"toward",
"towards",
"true",
"'twas",
"'tween",
"'twere",
"'twill",
"'twixt",
"two",
"'twould",
"u",
"under",
"underneath",
"unless",
"unlike",
"until",
"unto",
"up",
"upon",
"us",
"used",
"usually",
"v",
"versus",
"very",
"via",
"vice",
"vis-a-vis",
"w",
"wanna",
"wanting",
"was",
"wasn't",
"way",
"we",
"we'd",
"well",
"were",
"weren't",
"wert",
"we've",
"what",
"whatever",
"what'll",
"what's",
"when",
"whencesoever",
"whenever",
"when's",
"whereas",
"where's",
"whether",
"which",
"whichever",
"whichsoever",
"while",
"whilst",
"who",
"who'd",
"whoever",
"whole",
"who'll",
"whom",
"whore",
"who's",
"whose",
"whoso",
"whosoever",
"will",
"with",
"within",
"without",
"wont",
"would",
"wouldn't",
"wouldst",
"x",
"y",
"ye",
"yet",
"you",
"you'd",
"you'll",
"your",
"you're",
"yours",
"yourself",
"yourselves",
"you've",
"z",
private static Hashtable _stopwords=null;
public static object AddElement(IDictionary collection,Object key, object newValue)
object element = collection[key];
collection[key] = newValue;
return element;
public static bool IsStopword(string str)
//int index=Array.BinarySearch(stopWordsList, str)
return _stopwords.ContainsKey(str);
public StopWordsHandler()
if (_stopwords == null)
_stopwords = new Hashtable();
double dummy = 0;
foreach (string word in stopWordsList)
AddElement(_stopwords, word, dummy);
TFIDF.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1.appcode
class TFIDF
private string[] _docs;
private string[][] _ngramDoc;
private int _numDocs=0;
private int _numTerms=0;
private ArrayList _terms;
private int[][] _termFreq;
private float[][] _termWeight;
private int[] _maxTermFreq;
private int[] _docFreq;
public class TermVector
public static float ComputeCosineSimilarity(float[] vector1, float[] vector2)
if (vector1.Length != vector2.Length)
throw new Exception("DIFER LENGTH");
float denom=(VectorLength(vector1) * VectorLength(vector2));
if (denom == 0F)
return 0F;
else
return (InnerProduct(vector1, vector2) / denom);
public static float InnerProduct(float[] vector1, float[] vector2)
if (vector1.Length != vector2.Length)
throw new Exception("DIFFER LENGTH ARE NOT ALLOWED");
float result=0F;
for (int i=0; i < vector1.Length; i++)
result += vector1[i] * vector2[i];
return result;
public static float VectorLength(float[] vector)
float sum=0.0F;
for (int i=0; i < vector.Length; i++)
sum=sum + (vector[i] * vector[i]);
return (float)Math.Sqrt(sum);
private IDictionary _wordsIndex=new Hashtable() ;
public TFIDF(string[] documents)
_docs=documents;
_numDocs=documents.Length ;
MyInit();
private void GeneratNgramText()
private ArrayList GenerateTerms(string[] docs)
ArrayList uniques=new ArrayList() ;
_ngramDoc=new string[_numDocs][] ;
for (int i=0; i < docs.Length ; i++)
Tokeniser tokenizer=new Tokeniser() ;
string[] words=tokenizer.Partition(docs[i]);
for (int j=0; j < words.Length ; j++)
if (!uniques.Contains(words[j]) )
uniques.Add(words[j]) ;
return uniques;
private static object AddElement(IDictionary collection, object key, object newValue)
object element=collection[key];
collection[key]=newValue;
return element;
private int GetTermIndex(string term)
object index=_wordsIndex[term];
if (index == null) return -1;
return (int) index;
private void MyInit()
_terms=GenerateTerms (_docs );
_numTerms=_terms.Count ;
_maxTermFreq=new int[_numDocs] ;
_docFreq=new int[_numTerms] ;
_termFreq =new int[_numTerms][] ;
_termWeight=new float[_numTerms][] ;
for(int i=0; i < _terms.Count ; i++)
_termWeight[i]=new float[_numDocs] ;
_termFreq[i]=new int[_numDocs] ;
AddElement(_wordsIndex, _terms[i], i);
GenerateTermFrequency ();
GenerateTermWeight();
private float Log(float num)
return (float) Math.Log(num) ;//log2
private void GenerateTermFrequency()
for(int i=0; i < _numDocs ; i++)
string curDoc=_docs[i];
IDictionary freq=GetWordFrequency(curDoc);
IDictionaryEnumerator enums=freq.GetEnumerator() ;
_maxTermFreq[i]=int.MinValue ;
while (enums.MoveNext())
string word=(string)enums.Key;
int wordFreq=(int)enums.Value ;
int termIndex=GetTermIndex(word);
_termFreq [termIndex][i]=wordFreq;
_docFreq[termIndex] ++;
if (wordFreq > _maxTermFreq[i]) _maxTermFreq[i]=wordFreq;
private void GenerateTermWeight()
for(int i=0; i < _numTerms ; i++)
for(int j=0; j < _numDocs ; j++)
_termWeight[i][j]=ComputeTermWeight (i, j);
private float GetTermFrequency(int term, int doc)
int freq=_termFreq [term][doc];
int maxfreq=_maxTermFreq[doc];
return ( (float) freq/(float)maxfreq );
private float GetInverseDocumentFrequency(int term)
int df=_docFreq[term];
return Log((float) (_numDocs) / (float) df );
private float ComputeTermWeight(int term, int doc)
float tf=GetTermFrequency (term, doc);
float idf=GetInverseDocumentFrequency(term);
return tf * idf;
private float[] GetTermVector(int doc)
float[] w=new float[_numTerms] ;
for (int i=0; i < _numTerms; i++)
w[i]=_termWeight[i][doc];
return w;
public float GetSimilarity(int doc_i, int doc_j)
float[] vector1=GetTermVector (doc_i);
float[] vector2=GetTermVector (doc_j);
return TermVector.ComputeCosineSimilarity(vector1, vector2) ;
private IDictionary GetWordFrequency(string input)
//string convertedInput=input.ToLower() ;
Tokeniser tokenizer=new Tokeniser() ;
String[] words=tokenizer.Partition(input);
Array.Sort(words);
String[] distinctWords=GetDistinctWords(words);
IDictionary result=new Hashtable();
for (int i=0; i < distinctWords.Length; i++)
object tmp;
tmp=CountWords(distinctWords[i], words);
result[distinctWords[i]]=tmp;
return result;
private string[] GetDistinctWords(String[] input)
if (input == null)
return new string[0];
else
ArrayList list=new ArrayList() ;
for (int i=0; i < input.Length; i++)
if (!list.Contains(input[i])) // N-GRAM SIMILARITY?
list.Add(input[i]);
return Tokeniser.ArrayListToArray(list) ;
private int CountWords(string word, string[] words)
int itemIdx=Array.BinarySearch(words, word);
if (itemIdx > 0)
while (itemIdx > 0 && words[itemIdx].Equals(word))
itemIdx--;
int count=0;
while (itemIdx < words.Length && itemIdx >= 0)
if (words[itemIdx].Equals(word)) count++;
itemIdx++;
if (itemIdx < words.Length)
if (!words[itemIdx].Equals(word)) break;
return count;
Tokeniser.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1.appcode
class Tokeniser
public static string[] ArrayListToArray(ArrayList arraylist)
string[] array = new string[arraylist.Count];
for (int i = 0; i < arraylist.Count; i++) array[i] = (string)arraylist[i];
return array;
public string[] Partition(string input)
Regex r = new Regex("([ \\t{}():;. \n])");
//input = input.ToLower();
String[] tokens = r.Split(input);
ArrayList filter = new ArrayList();
for (int i = 0; i < tokens.Length; i++)
MatchCollection mc = r.Matches(tokens[i]);
if (mc.Count <= 0 && tokens[i].Trim().Length > 0
&& !StopWordsHandler.IsStopword(tokens[i]))
filter.Add(tokens[i]);
return ArrayListToArray(filter);
public Tokeniser()
button3 is compare functionality.in this scope i have to write similarity logic in terms of percentage.
oncle please check the code for similarty b/w the two pdf files.if any probelm please intimate.please help me.
thank u.Hi
Actually iText is a third party library to create PDF originally written for java. iTextSharp is the C# adaptation of that
library. Question regarding iText are better asked on the iText forum, but this is Microsoft Forum:
http://itextpdf.com/support
Thanks for your understanding.
Best regards,
Kristin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.
Maybe you are looking for
-
ExportPDF - "an error occurred while trying to access the service"
I have never had a problem using ExportPDF in the past but recently I am getting an error message saying "an error occurred while trying to access the service". I am using the same browser, Chrome, that I have always used. Please tell me how to fix
-
An error occurred while trying to save data to rhbag.apj
Opening a RoboHelp 8 project in new RoboHelp 11 and receive the following error: An error occurred while trying to save data to rhbag.apj... I can see this file in the project but many of my baggage files (.pdfs) are missing and I am not able to add
-
How do i combine two user accounts into one
how do i combine two user accounts into one
-
Does anyone know of any free programs to convert from .swf to another file type like mpg, avi, wmv, etc.
-
Update Java Sun JSDK 1.4.2_07 in server
Hello, I wonder if it is compulsory to use the version Sun JSDK 1.4.2_07 on the server xMII 11.5 or we can update the JAVA after installation of XMII 11.5 to a latest version of Java? We would have problems with support in SAP? Nilo ...