BinarySearch

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...

Similar Messages

  • [svn:osmf:] 14180: PARB changes: Move BinarySearch to layout package, it doesn't need to be part of the public API.

    Revision: 14180
    Revision: 14180
    Author:   [email protected]
    Date:     2010-02-15 21:52:51 -0800 (Mon, 15 Feb 2010)
    Log Message:
    PARB changes: Move BinarySearch to layout package, it doesn't need to be part of the public API.
    Modified Paths:
        osmf/trunk/framework/OSMF/.flexLibProperties
        osmf/trunk/framework/OSMF/org/osmf/layout/LayoutRendererBase.as
    Added Paths:
        osmf/trunk/framework/OSMF/org/osmf/layout/BinarySearch.as
        osmf/trunk/framework/OSMFTest/org/osmf/layout/TestBinarySearch.as
    Removed Paths:
        osmf/trunk/framework/OSMF/org/osmf/utils/BinarySearch.as
        osmf/trunk/framework/OSMFTest/org/osmf/utils/TestBinarySearch.as

    Revision: 14180
    Revision: 14180
    Author:   [email protected]
    Date:     2010-02-15 21:52:51 -0800 (Mon, 15 Feb 2010)
    Log Message:
    PARB changes: Move BinarySearch to layout package, it doesn't need to be part of the public API.
    Modified Paths:
        osmf/trunk/framework/OSMF/.flexLibProperties
        osmf/trunk/framework/OSMF/org/osmf/layout/LayoutRendererBase.as
    Added Paths:
        osmf/trunk/framework/OSMF/org/osmf/layout/BinarySearch.as
        osmf/trunk/framework/OSMFTest/org/osmf/layout/TestBinarySearch.as
    Removed Paths:
        osmf/trunk/framework/OSMF/org/osmf/utils/BinarySearch.as
        osmf/trunk/framework/OSMFTest/org/osmf/utils/TestBinarySearch.as

  • Problem with Collections.binarySearch()

    public class TaxPayerRecord implements Comparable <TaxPayerRecord>
    private String nric;
    private String name;
    private String dateOfBirth;
    private String gender;
    private String blockNo;
    private String unitNo;
    private String streetName;
    private String bldgName;
    private String postalCode;
    private long totalIncome;
    private long totalDonation;
    private long totalPersonalRelief;
    * Creates a new instance of TaxPayerRecord
    public TaxPayerRecord(String nric, String name, String dateOfBirth, String gender,
                   String blockNo, String unitNo, String streetName, String bldgName,
                   String postalCode, long totalIncome, long totalDonation,
                   long totalPersonalRelief)
    this.nric = nric;
    this.name = name;
    this.dateOfBirth = dateOfBirth;
    this.gender = gender;
    this.blockNo = blockNo;
    this.unitNo = unitNo;
    this.streetName = streetName;
    this.bldgName = bldgName;
    this.postalCode = postalCode;
    this.totalIncome = totalIncome;
    this.totalDonation = totalDonation;
    this.totalPersonalRelief = totalPersonalRelief;
    public String toString()
    return nric+"|"+name+"|"+dateOfBirth+"|"+gender+"|"+blockNo+"|"+unitNo+"|"+streetName+"|"+
    bldgName+"|"+postalCode+"|"+totalIncome+"|"+totalDonation+"|"+
    totalPersonalRelief;
    public long getTotalIncome()
    return totalIncome;
    public long getTotalDonation()
    return totalDonation;
    public long getTotalPersonalRelief()
    return totalPersonalRelief;
    public String getDateOfBirth()
    return dateOfBirth;
    public String getPostalCode()
    return postalCode;
    public int compareTo (TaxPayerRecord next)
              return this.nric.compareTo(next.nric);
    } //TaxPayerRecord
    import java.io.*;
    import java.util.*;
    public class TaxPayerProgramme
         public TaxPayerProgramme()
                             String menu = "Options: \n"
                                            + "1. Compute And Print List Of Tax Payers (Sorted by NRIC) \n"
                                            + "2. Compute And Summary Of Tax Revenue \n"
                                            + "3. Search for Tax Payer by NRIC \n"
                                            + "Enter option(1-2,0 to quit): ";
                             System.out.print(menu);
                             Scanner input = new Scanner( System.in );
                             int choice = input.nextInt();
                             System.out.println("");
                        // Declaration
                             ArrayList<TaxPayerRecord> list = new ArrayList<TaxPayerRecord>();
                             String inFile ="TaxPayer2005.txt";
                             String line = "";
                             String nric;
                             String name;
                             String dateOfBirth;
                             String gender;
                             String blockNo;
                             String unitNo;
                             String streetName;
                             String bldgName;
                             String postalCode;
                             long totalIncome;
                             long totalDonation;
                             long totalPersonalRelief;
                        try{
                             //Read from file
                             FileReader fr = new FileReader (inFile);
                             BufferedReader inFile1= new BufferedReader (fr);
                        line=inFile1.readLine();
                                       while (line!=null)
                                       StringTokenizer tokenizer = new StringTokenizer(line,"|");
                                       nric=tokenizer.nextToken();
                                       name=tokenizer.nextToken();
                                       dateOfBirth=tokenizer.nextToken();
                                       gender=tokenizer.nextToken();
                                       blockNo=tokenizer.nextToken();
                                       unitNo=tokenizer.nextToken();
                                       streetName=tokenizer.nextToken();
                                       bldgName=tokenizer.nextToken();
                                       postalCode=tokenizer.nextToken();
                                       totalIncome=Long.parseLong(tokenizer.nextToken());
                                       totalDonation=Long.parseLong(tokenizer.nextToken());
                                       totalPersonalRelief=Long.parseLong(tokenizer.nextToken());
                                       TaxPayerRecord person = new TaxPayerRecord(nric,name,dateOfBirth,gender,blockNo,unitNo,
                                                                                              streetName,bldgName,postalCode,totalIncome,
                                                                                              totalDonation,totalPersonalRelief);
                                       list.add(person);
                                       line=inFile1.readLine();
                                       }//end while
                        inFile1.close();
                             }// end try
                        catch (Exception e)
                             e.printStackTrace();
                        }//end catch
                        do{
                                  switch(choice)
                                       case 0:
                                       System.exit(0);
                                       break;
                                       case 1:
                                       // run list
                                       printList(list);
                                       break;
                                       case 2:
                                       printSummary(list);
                                       break;
                                       case 3:
                                       search(list,input);
                                       break;
                                  }//end switch
                             System.out.print(menu);
                             choice = input.nextInt();
                             System.out.println("");
                             }// end do
                             while(choice !=0);
                             Collections.sort(list);
         }//end TaxPayerProgramme()
         private void total(ArrayList<TaxPayerRecord> list)
              // Declaration
              double total=0;
              // calculate total
                   for (int i=0; i<list.size(); i++)
                   total=+ tax(i,list);
              //print msg
              System.out.println("Total revenue collectable for year 2006 (S$): "+total+"\n");
         private double tax(int i,ArrayList<TaxPayerRecord> list)
              // Declaration
              double income;
              double tax;
              // calculate income
              income =list.get(i).getTotalIncome()-list.get(i).getTotalDonation()
                        -list.get(i).getTotalPersonalRelief();
              // calculate tax
                   if (income>320000)
                        tax=(((income-320000)*0.21)+44850);
                   else if (income>160000)
                        tax=(((income-160000)*0.18)+16050);
                   else if (income>80000)
                        tax=(((income-80000)*0.145)+4450);
                   else if (income>40000)
                        tax=(((income-40000)*0.0875)+950);
                   else if (income>30000)
                        tax=(((income-30000)*0.0577)+375);
                   else
                        tax=((income-20000)*0.0577);
              return tax;
         private void totalAge(ArrayList<TaxPayerRecord> list)
                   // Declaration
                   String msg;
                   int i,age;
                   double grp1=0;
                   double grp2=0;
                   double grp3=0;
                   double grp4=0;
                   // calculate revenue by age
                        for (i=0; i<list.size(); i++)
                        age= 2006- Integer.parseInt(list.get(i).getDateOfBirth().substring(6,list.get(i).getDateOfBirth().length()));
                        if (age>55)
                             grp4 =+ tax(i,list);
                        else if (age>35)
                             grp3 =+ tax(i,list);
                        else if (age>17)
                             grp2 =+ tax(i,list);
                        else
                             grp1 =+ tax(i,list);
                   //print msg
                   msg="Total revenue by age range (S$) \n"+
                        "\t"+"(1 to 17)"+"\t"+ grp1 +"\n"     +
                        "\t"+"(18 to 35)"+"\t"+ grp2 +"\n"     +
                        "\t"+"(36 to 55)"+"\t"+ grp3 +"\n"     +
                        "\t"+"(above 55)"+"\t"+ grp4 +"\n";
                   System.out.println(msg);
    private void totalDistrict(ArrayList<TaxPayerRecord> list)
                   int count=1;
                   double temp=0;
                   double [][] array = new double [list.size()][2];
                        for (int i=0; i<list.size(); i++)
                        array[0]=Double.parseDouble(list.get(i).getPostalCode().substring(0,2));
                        array[i][1]=tax(i,list);
                   System.out.println("Total revenue by district (S$) ");
                        do{
                                  for (int a=0; a<list.size(); a++)
                                       if (count == array[a][0] )
                                       temp=array[a][1];
                                  }//end for loop
                             System.out.print("\t"+"(district "+count+")"+"\t"+ temp +"\n");
                             temp=0;
                             count++;
                        }while(count!= 80);// end of do_while loop
              System.out.print("\n");
         private void printList(ArrayList<TaxPayerRecord> list)
              System.out.println("List of Tax Payers fpr Year 2006");
                   for (int i=0; i<list.size(); i++)
                   System.out.println((i+1)+") "+list.get(i)+"|"+tax(i,list)+"\n");
         private void printSummary(ArrayList<TaxPayerRecord> list)
                   total(list);
                   totalAge(list);
                   totalDistrict(list);
         private void search(ArrayList<TaxPayerRecord> list,Scanner input)
                   String nric;
                   int value;
                   System.out.print("Enter NRIC Number: ");
                   nric = input.next();
                   Collections.sort(list);
                   value = Collections.binarySearch(list,nric);
         public static void main(String [] args)
                   new TaxPayerProgramme();
    I keep getting this message:
    C:\Documents and Settings\Xiong\Desktop\TaxPayerProgramme.java:285: cannot find symbol
    symbol : method binarySearch(java.util.ArrayList<TaxPayerRecord>,java.lang.String)
    location: class java.util.Collections
                   value = Collections.binarySearch(list,nric);
                   ^
    1 error
    Tool completed with exit code 1

    You can't search a list of TacPayerRecords using a String.

  • Problem with binarySearch method

    In the code below I've got a problem with my binarySearach method in the IntegerList.java file. When I look at my IntegerTest file, Eclipse give me this message next to my method call for the binarySerch (case 6): (the method binarySearch int[] , int) in the type integerList is not applicable for the arguments (int). So what the heck have I done wrong? I know it's a lot of code to look at but felt you'll need to see both classes to make heads or tales out of this.
    Thanks in advance.
    import java.util.Scanner;
    public class IntegerList //implements Comparable
         int [] list; // values in the list
         //Constructor -- takes an integer and creates a list of that
         //size.  All elements default to value 0.
         public IntegerList(int size)
              list = new int[size];
         //randomize -- fills the array with randomly generated integers
         //between 1 and 100, inclusive
         public void randomize()
              int max = list.length;
              for (int i=0; i < list.length; i++)
                   list[i] = (int) (Math.random() * max) +1;
         //fillSorted -- fills the array with sorted values
         public void fillSorted()
              for (int i =0; i <list.length; i++)
                   list = i + 2;
         //print -- prints array elements with indices, one per line
         public String toString()
              String s = "";
              for (int i = 0; i <list.length; i++)
                   s += i + ":\t" + list[i] + "\n";
              return s;
         //linearSearch -- takes a target value and returns the index
         //of the first occurrence of target in the list. Returns -1
         //if target does not appear in the list
         public int linearSearch (int target)
              int location = -1;
              for (int i = 0; i < list.length && location == -1; i++)
                   if (list [i] == target)
                        location = i;
                   return location;
         //sortIncresing -- uses selection sort
         public void sortIncreasing()
              for (int i =0; i < list.length -1; i++)
                        int minIndex = minIndex(list, i);
                        swap (list, i, minIndex);
    private void swap(int[] list, int index, int min)
    int temp =list [index];
    list [index] = list [min];
    list [min] = temp;
    // private int minIndex(int[] list, int index)
    public int minIndex(int[] list, int lastIndex) {
    int min=list[lastIndex];
    for (int i=lastIndex+1; i<list.length; i++)
    if (list[i]<min)
    lastIndex=i;
    return lastIndex;
    public void sortDecreasing()
              for (int i =0; i > list.length -1; i++)
                        int minIndex = minIndex(list, i);
                        swap (list, i, minIndex);
    public static int binarySearch (int [] list, int val)
    int min = 0, max = list.length, mid =0;
    boolean found = false;
    while (!found && min <= max)
    mid = (min + max) / 2;
    if (list [mid]== val)
    found = true;
         //if the mid point contains the value being searched for
         //then we are done
    else
    if (list[mid]< val)
    max = mid -1;
    else
    min = mid+1;
    if (found)
    return list[mid];
    else
    return -1;
    return val;
    }//end class
    //now for the IntegerListTest class
         //File: integerListTest.java
         //Purpose: Provide a menu-driven tester for the IntegerList class.
         import java.util.*;
         public class IntegerListTest
              static IntegerList list = new IntegerList(10);
              static Scanner scan = new Scanner(System.in);
         // main -- creates an initial list, then repeatedly prints
         // the menu and does what the user asks until they quit
         public static void main(String [] args)
              printMenu();
              int choice = scan.nextInt();
              while (choice != 0)
                        dispatch(choice);
                        printMenu();
                        choice = scan.nextInt();
         // dispatch -- takes a choice and does what needs doing
         public static void dispatch(int choice)
              int loc;
              int val;
              long time1, time2;
              long totalTime;
              switch (choice)
                        case 0:
                             System.out.println("Bye!");
                             break;
                        case 1:
                             System.out.println(list);
                             break;
                        case 2:
                             System.out.println("How big should the list be?");
                             list = new IntegerList (scan.nextInt());
                             System.out.println("List is created.");
                             break;
                        case 3:
                             list.randomize();
                             System.out.println("List is filled with random elements.");
                             break;
                        case 4:
                             list.fillSorted();
                             System.out.println("List is filled with sorted elements.");
                             break;
                        case 5:
                             System.out.print("Enter the value to look for: ");
                             val = scan.nextInt();
                             time1 = System.currentTimeMillis();
                             loc = list.linearSearch(val);
                             time2 = System.currentTimeMillis();
                             totalTime = time1 - time2;
                             System.out.print(totalTime);
                             if (loc != -1)
                                  System.out.println("Found at location " + loc);
                             else
                                  System.out.println("Not in list");
                             break;
                        case 6:
                             System.out.print("Enter the value to look for: ");
                             val = scan.nextInt();
                             loc = list.binarySearch(val);
                             if (loc != -1)
                                  System.out.println("Found at location " + loc);
                             else
                                  System.out.println("Not in list");
                             break;
                        case 7:
                             list.sortIncreasing();
                             System.out.println("List has been sorted.");
                             break;
                        case 8:
                             list.sortDecreasing();
                             System.out.println("List has been sorted.");
                             break;
                        default:
                             System.out.println("Sorry, invalid choice");
         // printMenu -- prints the user's choices
         public static void printMenu()
              System.out.println("\n Menu ");
              System.out.println(" ====");
              System.out.println("0: Quit");
              System.out.println("1: Print the list");
              System.out.println("2: Create a new list of a given size");
              System.out.println("3: Fill the list with random ints in range 1-length");
              System.out.println("4: Fill the list with already sorted elements");
              System.out.println("5: Use linear search to find an element");
              System.out.println("6: Use binary search to find an element " +
                                  "(list must be sorted in increasing order)");
              System.out.println("7: Use selection sort to sort the list into " +
                                  " increasing order");
              System.out.println("8: Use insertion sort to sort the list into " +
                                  " decreasing order");
              System.out.println("\nEnter your choice: ");

    Ah... But now that I have looked at it some more, I have noticed that the array of int is created in your IntegerList class...
    so you want to change your binarySearch() method...
    from...
    public static int binarySearch (int[] list,int val)to
    public int binarySearch (int val)now it will search the list declared in your constructor...
    and also note that static is remove to eliminate the non-static reference from static context error...
    so in IntegerList.java, that method signature should look like this...
    public int binarySearch (int val)// take only one arguement and...
    // check against internal int [] listand you call it like this...
    loc = list.binarySearch(val);// not changednow all you have to do it get your list populated with random integers for the rest to work... I leave that to you...
    - MaxxDmg...
    - ' He who never sleeps... '

  • 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,
    Babu

    hi 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));

  • Question regarding Collections.binarySearch()

    I was looking at the source of the binarySearch implementation, and while most of it is perfectly clear, I just don't get why the method
    returns -(low 1)+ instead of -low when the desired item has not been found.
    The doc says it should return in this case -(insertionpoint) - 1 but this makes no sense for me.
    Thanks in advance :-).

    Well done figuring it out. It gives a good sense of satisfaction to lead someone to the answer instead of just spoon-feeding like most posters seem to expect!
    BTW: It does also explain that in the Javadoc ;-)
    (And don't forget the dukes...)

  • 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.

  • Need Help With Collection.binarySearch ! Please help me

    * TaxPayerRecord.java
    * Created on December 21, 2006, 11:42 AM
    public class TaxPayerRecord implements Comparable <TaxPayerRecord>
        private String nric;
        private String name;
        private String dateOfBirth;
        private String gender;
        private String blockNo;
        private String unitNo;
        private String streetName;
        private String bldgName;
        private String postalCode;
        private long totalIncome;
        private long totalDonation;
        private long totalPersonalRelief;
         * Creates a new instance of TaxPayerRecord
        public TaxPayerRecord(String nric, String name, String dateOfBirth, String gender,
                                 String blockNo, String unitNo, String streetName, String bldgName,
                                 String postalCode, long totalIncome, long totalDonation,
                                 long totalPersonalRelief)
            this.nric = nric;
            this.name = name;
            this.dateOfBirth = dateOfBirth;
            this.gender = gender;
            this.blockNo = blockNo;
            this.unitNo = unitNo;
            this.streetName = streetName;
            this.bldgName = bldgName;
            this.postalCode = postalCode;
            this.totalIncome = totalIncome;
            this.totalDonation = totalDonation;
            this.totalPersonalRelief = totalPersonalRelief;
        public String toString()
            return nric+"|"+name+"|"+dateOfBirth+"|"+gender+"|"+blockNo+"|"+unitNo+"|"+streetName+"|"+
                   bldgName+"|"+postalCode+"|"+totalIncome+"|"+totalDonation+"|"+
                   totalPersonalRelief;
        public long getTotalIncome()
            return totalIncome;
        public long getTotalDonation()
            return totalDonation;
        public long getTotalPersonalRelief()
            return totalPersonalRelief;
        public String getDateOfBirth()
            return dateOfBirth;
        public String getPostalCode()
            return postalCode;
        public int compareTo (TaxPayerRecord next)
              return this.nric.compareTo(next.nric);
    } //TaxPayerRecord
    import java.io.*;
    import java.util.*;
    public class TaxPayerProgramme
         public TaxPayerProgramme()
                             String menu = "Options: \n"
                                            + "1. Compute And Print List Of Tax Payers (Sorted by NRIC) \n"
                                            + "2. Compute And Summary Of Tax Revenue \n"
                                            + "3. Search for Tax Payer by NRIC \n"
                                            + "Enter option(1-2,0 to quit): ";
                             System.out.print(menu);
                             Scanner input = new Scanner( System.in );
                             int choice = input.nextInt();
                             System.out.println("");
                         // Declaration
                             ArrayList<TaxPayerRecord> list = new ArrayList<TaxPayerRecord>();
                             String inFile ="TaxPayer2005.txt";
                             String line = "";
                             String nric;
                             String name;
                             String dateOfBirth;
                             String gender;
                             String blockNo;
                             String unitNo;
                             String streetName;
                             String bldgName;
                             String postalCode;
                             long totalIncome;
                             long totalDonation;
                             long totalPersonalRelief;
                        try{
                             //Read from file
                             FileReader fr = new FileReader (inFile);
                             BufferedReader inFile1= new BufferedReader (fr);
                             line=inFile1.readLine();
                                       while (line!=null)
                                       StringTokenizer tokenizer = new StringTokenizer(line,"|");
                                       nric=tokenizer.nextToken();
                                       name=tokenizer.nextToken();
                                       dateOfBirth=tokenizer.nextToken();
                                       gender=tokenizer.nextToken();
                                       blockNo=tokenizer.nextToken();
                                       unitNo=tokenizer.nextToken();
                                       streetName=tokenizer.nextToken();
                                       bldgName=tokenizer.nextToken();
                                       postalCode=tokenizer.nextToken();
                                       totalIncome=Long.parseLong(tokenizer.nextToken());
                                       totalDonation=Long.parseLong(tokenizer.nextToken());
                                       totalPersonalRelief=Long.parseLong(tokenizer.nextToken());
                                       TaxPayerRecord person = new TaxPayerRecord(nric,name,dateOfBirth,gender,blockNo,unitNo,
                                                                                              streetName,bldgName,postalCode,totalIncome,
                                                                                              totalDonation,totalPersonalRelief);
                                       list.add(person);
                                       line=inFile1.readLine();
                                       }//end while
                              inFile1.close();
                             }// end try
                        catch (Exception e)
                              e.printStackTrace();
                        }//end catch
                        do{
                                  switch(choice)
                                       case 0:
                                       System.exit(0);
                                       break;
                                       case 1:
                                       // run list
                                       printList(list);
                                       break;
                                       case 2:
                                       printSummary(list);
                                       break;
                                       case 3:
                                       search(list,input);
                                       break;
                                  }//end switch
                             System.out.print(menu);
                             choice = input.nextInt();
                             System.out.println("");
                             }// end do
                             while(choice !=0);
                             Collections.sort(list);
         }//end TaxPayerProgramme()
         private void total(ArrayList<TaxPayerRecord> list)
              // Declaration
              double total=0;
              // calculate total
                   for (int i=0; i<list.size(); i++)
                   total=+ tax(i,list);
              //print msg
              System.out.println("Total revenue collectable for year 2006 (S$): "+total+"\n");
         private double tax(int i,ArrayList<TaxPayerRecord> list)
              // Declaration
              double income;
              double tax;
              // calculate income
              income =list.get(i).getTotalIncome()-list.get(i).getTotalDonation()
                        -list.get(i).getTotalPersonalRelief();
              // calculate tax
                   if (income>320000)
                        tax=(((income-320000)*0.21)+44850);
                   else if (income>160000)
                        tax=(((income-160000)*0.18)+16050);
                   else if (income>80000)
                        tax=(((income-80000)*0.145)+4450);
                   else if (income>40000)
                        tax=(((income-40000)*0.0875)+950);
                   else if (income>30000)
                        tax=(((income-30000)*0.0577)+375);
                   else
                        tax=((income-20000)*0.0577);
              return tax;
         private void totalAge(ArrayList<TaxPayerRecord> list)
                   // Declaration
                   String msg;
                   int i,age;
                   double grp1=0;
                   double grp2=0;
                   double grp3=0;
                   double grp4=0;
                   // calculate revenue by age
                        for (i=0; i<list.size(); i++)
                        age= 2006- Integer.parseInt(list.get(i).getDateOfBirth().substring(6,list.get(i).getDateOfBirth().length()));
                        if (age>55)
                             grp4 =+ tax(i,list);
                        else if (age>35)
                             grp3 =+ tax(i,list);
                        else if (age>17)
                             grp2 =+ tax(i,list);
                        else
                             grp1 =+ tax(i,list);
                   //print msg
                   msg="Total revenue by age range (S$) \n"+
                        "\t"+"(1 to 17)"+"\t"+ grp1 +"\n"     +
                        "\t"+"(18 to 35)"+"\t"+ grp2 +"\n"     +
                        "\t"+"(36 to 55)"+"\t"+ grp3 +"\n"     +
                        "\t"+"(above 55)"+"\t"+ grp4 +"\n";
                   System.out.println(msg);
        private void totalDistrict(ArrayList<TaxPayerRecord> list)
                   int count=1;
                   double temp=0;
                   double [][] array = new double [list.size()][2];
                        for (int i=0; i<list.size(); i++)
                        array[0]=Double.parseDouble(list.get(i).getPostalCode().substring(0,2));
                        array[i][1]=tax(i,list);
                   System.out.println("Total revenue by district (S$) ");
                        do{
                                  for (int a=0; a<list.size(); a++)
                                       if (count == array[a][0] )
                                       temp=array[a][1];
                                  }//end for loop
                             System.out.print("\t"+"(district "+count+")"+"\t"+ temp +"\n");
                             temp=0;
                             count++;
                        }while(count!= 80);// end of do_while loop
              System.out.print("\n");
         private void printList(ArrayList<TaxPayerRecord> list)
              System.out.println("List of Tax Payers fpr Year 2006");
                   for (int i=0; i<list.size(); i++)
                   System.out.println((i+1)+") "+list.get(i)+"|"+tax(i,list)+"\n");
         private void printSummary(ArrayList<TaxPayerRecord> list)
                   total(list);
                   totalAge(list);
                   totalDistrict(list);
         private void search(ArrayList<TaxPayerRecord> list,Scanner input)
                   int value;
                   System.out.print("Enter NRIC Number: ");
                   String nric = input.next();
                   Collections.sort(list);
                   value = Collections.binarySearch(list,nric);
         public static void main(String [] args)
                   new TaxPayerProgramme();
    Can someone help me with this?
    I can't find the error.
    The error msg display:
    C:\Documents and Settings\Xiong\Desktop\TaxPayerProgramme.java:285: cannot find symbol
    symbol : method binarySearch(java.util.ArrayList<TaxPayerRecord>,java.lang.String)
    location: class java.util.Collections
                   value = Collections.binarySearch(list,nric);
                   ^
    1 error
    Tool completed with exit code 1

    Well, this is the error, Java6 gives me on your code:The method binarySearch(List< ? extends Comparable<? super T> >, T) in the type Collections
    is not applicable for the arguments (ArrayList<TaxPayerRecord>, String)     The method expects the first parameter, to be a List whose children are Comparable to the second parameter. Your second parameter is String, so the List should be on String not on TaxPayerRecord, or, your second parameter should be a TaxPayerRecord and not a String.
    �dit: Another thought. From the error code you posted, I would assume, that you might have the wrong JDK libraries in your path.

  • Using Collections.binarySearch on a Linked list

    hi all
    i want to use the Collections.binarySearch method on a linked list object to add items to it. These items are of type Entry (a class i have created).
    i have the following code:
    public void addEntry(Entry newEntry)
            int pos = Collections.binarySearch(entryList, newEntry);
            if (pos < 0)
                entryList.add(-(pos) -1, newEntry);
    [\CODE]
    where entryList is declared as:
    private List entryList = new LinkedList();
    This code compiles OK, but when i run it to add an Entry element to the linked list, i get a ClassCastException being thrown, and im not sure why.
    i can add one Entry object to the list ok, but it falls over when i try to add another. im trying to order my Entry objects by a field called 'surname', so the binarySearch finds the correct location in the list for the new entry and then it is added.
    any help on this would be appreciated
    cheers
    david                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    binarySearch doesn't work on a linked listSo untrue:Well, only mostly untrue. It still doesn't really do a binary search on your linked list
    From the javadoc
    'This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. '
    import java.util.*;
    public class Test {
    public static void main(String[] args) {
    List entryList = new LinkedList();
    entryList.add(new Integer(3));
    entryList.add(new Integer(5));
    entryList.add(new Integer(1));
    Collections.sort(entryList);
    System.out.println(Collections.binarySearch(entryList,
    new Integer(5)));
    }Compiles and runs without any problems

  • Please help with Boggle game

    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 advance

    Ok, 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

  • How to ask for an array and how to save the values

    I'm supposed to be learning the differences between a linear search and a binary search, and the assignment is to have a user input an array and search through the array for a given number using both searches. My problem is that I know how to ask them how long they want their array to be, but I don't know how to call the getArray() method to actually ask for the contents of the array.
    My code is as follows:
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How long would you like the array to be?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            System.out.println("Please enter the first value of the array");
        public static void getArray(int List[], int arrayLength)
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter the next value for array");
                 List[i] = input.nextInt();
         public static void printArray(int List[])
             for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
    public class search
        public static int binarySearch(int anArray[], int first, int last, int value)
            int index;
            if(first > last) {
                index = -1;
            else {
                int mid = (first + last)/2;
                if(value == anArray[mid]) {
                    index = mid; //value found at anArray[mid]
                else if(value < anArray[mid]) {
                    //point X
                    index = binarySearch(anArray, first, mid-1, value);
                else {
                    //point Y
                    index = binarySearch(anArray, mid+1, last, value);
                } //end if
            } //end if
            return index;
        //Iterative linear search
        public int linearSearch(int a[], int valueToFind)
            //valueToFind is the number that will be found
            //The function returns the position of the value if found
            //The function returns -1 if valueToFind was not found
            for (int i=0; i<a.length; i++) {
                if (valueToFind == a) {
    return i;
    return -1;

    I made the changes. Two more questions.
    1.) Just for curiosity, how would I have referenced those methods (called them)?
    2.) How do I call the searches?
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How many values would you like the array to have?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            //Collects the array information
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter a value for array");
                 List[i] = input.nextInt(); 
            //Prints the array
            System.out.print("Array: ");
            for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
            //Asks for the value to be searched for
            System.out.println("What value would you like to search for?");
            int temp = input.nextInt();
            System.out.println(search.binarySearch()); //not working
    }

  • Word Puzzle still not working

    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.
    Wulf

    Your 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 to use a standard library binary search if I'm not searching for a key?

    Hi all,
    I'm looking for the tidiest way to code something with maximum use of the standard libraries. I have a sorted set of ints that represent quality levels (let's call the set qualSet ). I want to find the maximum quality level (choosing only from those within qualSet ) for a limited budget. I have a method isAffordable(int) that returns boolean. So one way to find the highest affordable quality is to start at the lowest quality level, iterate through qualSet (it is sorted), and wait until the first time that isAffordable returns false. eg.
    int i=-1;
    for (int qual : qualSet) {
         if !(isAffordable(qual))
              return i;
         i++;
    }However isAffordable is a slightly complicated fn, so I'd like to use a binary search to make the process more efficient. I don't want to write the code for a binary search as that is something that should be reused, ideally from the standard libraries. So my question is what's the best way of reusing standard library code in this situation so as to not write my own binary search?
    I have a solution, but I don't find it very elegant. Here are the important classes and objects.
    //simple wrapper for an int representing quality level
    class QualityElement implements Comparable<QualityElement>
    //element to use to search for highest quality
    class HiQualFinderEl extends QualityElement {
         HiQualFinderEl(ComponentList cl) {...}
    //class that contains fair amount of data and isAffordable method
    class ComponentList {
         boolean isAffordable(int qual) {...}
    //sorted set of QualityElements
    TreeSet<QualityElement> qualSet When you create an instance of HiQualFinderEl, you pass it a reference to a ComponentList (because it has the isAffordable() method). The HiQualFinderEl.compareTo() function returns 1 or -1 depending on whether the QualityElement being compared to is affordable or not. This approach means that the binary search returns an appropriate insertion point within the list (it will never act as if it found the key).
    I don't like this because semantically the HiQualFinderEl is not really an element of the list, it's certainly not a QualityElement (but it inherits from it), and it just feels ugly! Any clever suggestions? Btw, I'm new to Java, old to C++.
    If this is unclear pls ask,
    Andy

    Thanks Peter for the reply
    Peter__Lawrey wrote:
    you are not looking for a standard binary searchI'm not using a binary search in the very common I'm searching for a particular key sense, which is the Collections.binarySearch sense. But binary searches are used in other situations as well. In this case I'm finding a local maximum of a function, I could also be solving f(x)=0... is there a nice generic way to handle other uses of binary search that anyone knows of?
    I would just copy the code from Collections.binarySearch and modify itI have this thing about reusing; just can't bring myself to do that :)
    It would be quicker and more efficient than trying to shoe horn a solution which expects a trinary result.Not sure I understand the last bit. Are you referring to my bastardised compareTo method with only two results? If so, I know, it is ugly! I don't see how it could be less efficient though???
    Thanks,
    Andy

  • How to Use a Binary Library

    Hi,
    I am trying to use a binary library (Xerces 2.9.0). I would like to know if there is a way to use this library by putting it in my project path and using an import statement to do so. I did this with a version of entagged and placed it in "lib\\entagged" (where my compiled classes are located) and used the folder hierarchy:
    import lib.entagged.*;Is it possible to do the same with a binary package as in the image linked here:
    http://img251.imageshack.us/img251/441/xercesnm4.jpg
    This would make it easier to compile and use across multiple computers...
    Thanks in advance

    Thanks Peter for the reply
    Peter__Lawrey wrote:
    you are not looking for a standard binary searchI'm not using a binary search in the very common I'm searching for a particular key sense, which is the Collections.binarySearch sense. But binary searches are used in other situations as well. In this case I'm finding a local maximum of a function, I could also be solving f(x)=0... is there a nice generic way to handle other uses of binary search that anyone knows of?
    I would just copy the code from Collections.binarySearch and modify itI have this thing about reusing; just can't bring myself to do that :)
    It would be quicker and more efficient than trying to shoe horn a solution which expects a trinary result.Not sure I understand the last bit. Are you referring to my bastardised compareTo method with only two results? If so, I know, it is ugly! I don't see how it could be less efficient though???
    Thanks,
    Andy

Maybe you are looking for

  • Album sort order suddenly gone crazy iTunes

    G'day people For some reason, the last couple of albums I've downloaded from the iTunes store, to my iTunes, displays those albums groups by artist instead of album. Even when I select them an manually change the sort order it makes no difference. Pr

  • Best Practice Attaching USB drive to VM

    Since USB passthru is no longer supported in OVM, what is the best practice and or recommendation for loading large amounts of data to a VM from an external USB drive? 

  • Limit on Attachment Size in Mail

    I want to receive mails with a text file attachment (.csv file).  I receive it OK and can view the attachment in the mail if the attachment is just a few lines, but i don't receive the mail at all if the attachment is a little larger.  Is there a lim

  • Java vulnerability on Internet Explorer?

    I've noticed that when I try to enter a certain site with Internet Explorer a Java written virus tries to attack me. Does anyone know anything about this? How can I fix it?

  • Creative Muvo2 FM freezing on start

    Hi everyone, If anyone can help me with this I'd greatly appreciate it. My muvo froze the other day on a song, and wouldn't turn off - after removing the battery and replacing it, it gets stuck on the 'Muvo2 FM' screen won't do anything else, and it