Implement a greedy search in java
Implement a greedy serch in java for the map of romania .goal state is bucharest.
1.not to visit the same city twice
2.give the search trees
3.try 3 initial states
No. Do it yourself. This is a help forum, not a "here's my requirements do it for me" forum.
Similar Messages
-
Greedy Search implementation for the Map of Romania
hi folks!im totally new to Java / Linux and the U.S!!I have slight knowledge of c# though.Can anyone point me towards the right direction for this problem?The famous Romania map is killin me ;)
Was given only 5 days for this assignment.Pl help me with this and eventually my grades :)
Thank you for reading...
Problem: Implement a greedy search in Java, given the map of Romania.. The
goal state is Bucharest.
You are not to visit the same city twice.
Provide the search trees.
Try three initial states.
Evaluate your solutions.
Use the Romania map with Straight Line distances.
Map of Romania :: https://kirankonathala.sslpowered.com/kirankonathala.com/AI/MapOfRomania.jpg
Straight Line Distances :: https://kirankonathala.sslpowered.com/kirankonathala.com/AI/straightLineDistances.JPGHI Guys!Pl comment on this code -- Is it a good practice to build the tree as described here??my friend provided me this.can't we avoid hashmaps?
Pl comment...
class GreedySearch
public static void main(String a[]){
HashMap stateMap = new HashMap();
ArrayList stateList = new ArrayList();// this list is used to get the city name based on the user input
State arad = new State("Arad",366);
arad.addNextState("Timisoara",329,118);
arad.addNextState("Sibiu",253,140);
arad.addNextState("Zerind",374,75);
State bucharest = new State("Bucharest",0);
bucharest.addNextState("Glurglu",77,90);
bucharest.addNextState("Urziceni",80,85);
bucharest.addNextState("Fagaras",176,211);
bucharest.addNextState("Pitesti",100,101);
State cralova = new State("Cralova",160);
cralova.addNextState("Pitesti",100,138);
cralova.addNextState("Rimnicu",193,146);
cralova.addNextState("Dobreta",242,120);
State dobreta = new State("Dobreta",242);
dobreta.addNextState("Cralova",160,120);
dobreta.addNextState("Mehadia",241,75);
State eforle = new State("Eforle",161);
eforle.addNextState("Hirsova",151,86);
State fagaras = new State("Fagaras",176);
fagaras.addNextState("Bucharest",0,211);
fagaras.addNextState("Sibiu",253,99);
State glurglu = new State("Glurglu",77);
glurglu.addNextState("Bucharest",0,90);
State hirsova = new State("Hirsova",151);
hirsova.addNextState("Urziceni",80,98);
hirsova.addNextState("Eforle",161,86);
State iasi = new State("Iasi",226);
iasi.addNextState("Vaslui",199,92);
iasi.addNextState("Neamt",234,87);
State lugoj = new State("Lugoj",244);
lugoj.addNextState("Mehadia",241,70);
lugoj.addNextState("Timisoara",329,111);
State mehadia = new State("Mehadia",241);
mehadia.addNextState("Dobreta",242,75);
mehadia.addNextState("Lugoj",244,70);
State neamt = new State("Neamt",234);
neamt.addNextState("Iasi",226,87);
State oradea = new State("Oradea",380);
oradea.addNextState("Sibiu",253,151);
oradea.addNextState("Zerind",374,71);
State pitesti = new State("Pitesti",100);
pitesti.addNextState("Bucharest",0,101);
pitesti.addNextState("Cralova",160,138);
pitesti.addNextState("Rimnicu",193,97);
State rimnicu = new State("Rimnicu",193);
rimnicu.addNextState("Sibiu",253,80);
rimnicu.addNextState("Pitesti",100,97);
rimnicu.addNextState("Cralova",160,146);
State sibiu = new State("Sibiu",253);
sibiu.addNextState("Fagaras",176,99);
sibiu.addNextState("Rimnicu",193,80);
sibiu.addNextState("Arad",366,140);
sibiu.addNextState("Oradea",380,151);
State timisoara = new State("Timisoara",329);
timisoara.addNextState("Lugoj",244,111);
timisoara.addNextState("Arad",366,118);
State urziceni = new State("Urziceni",80);
urziceni.addNextState("Bucharest",0,85);
urziceni.addNextState("Hirsova",151,98);
urziceni.addNextState("Vaslui",199,142);
State vaslui = new State("Vaslui",199);
vaslui.addNextState("Urziceni",80,142);
vaslui.addNextState("Iasi",226,92);
State zerind = new State("Zerind",374);
zerind.addNextState("Arad",366,75);
zerind.addNextState("Oradea",380,71);
stateMap.put("Arad",arad);
stateMap.put("Cralova",cralova);
stateMap.put("Dobreta",dobreta);
stateMap.put("Eforle",eforle);
stateMap.put("Fagaras",fagaras);
stateMap.put("Glurglu",glurglu);
stateMap.put("Hirsova",hirsova);
stateMap.put("Iasi",iasi);
stateMap.put("Lugoj",lugoj);
stateMap.put("Mehadia",mehadia);
stateMap.put("Neamt",neamt);
stateMap.put("Oradea",oradea);
stateMap.put("Pitesti",pitesti);
stateMap.put("Rimnicu",rimnicu);
stateMap.put("Sibiu",sibiu);
stateMap.put("Timisoara",timisoara);
stateMap.put("Urziceni",urziceni);
stateMap.put("Vaslui",vaslui);
stateMap.put("Zerind",zerind);
stateList.add("Arad");// this list is used to get the city name based on the user input
stateList.add("Cralova");
stateList.add("Dobreta");
stateList.add("Eforle");
stateList.add("Fagaras");
stateList.add("Glurglu");
stateList.add("Hirsova");
stateList.add("Iasi");
stateList.add("Lugoj");
stateList.add("Mehadia");
stateList.add("Neamt");
stateList.add("Oradea");
stateList.add("Pitesti");
stateList.add("Rimnicu");
stateList.add("Sibiu");
stateList.add("Timisoara");
stateList.add("Urziceni");
stateList.add("Vaslui");
stateList.add("Zerind");
System.out.println(" 1) Arad \n 2) Cralova\n 3) Dobreta\n 4) Eforle\n 5) Fagaras\n 6) Glurglu\n"
+" 7) Hirsova\n 8) Iasi\n 9) Lugoj\n 10) Mehadia\n 11) Neamt\n 12) Oradea\n 13) Pitesti\n"
+" 14) Rimnicu\n 15) Sibiu\n 16) Timisoara\n 17) Urziceni\n 18) Vaslui \n 19) Zerind\n ");
System.out.print("Enter the starting State: "); -
Manhattan distance Greedy search
Hi all,
I am developing a program to solve the 8 puzzle using the greedy search.
I have two 2D arrays(sorry about the code) -
public static int [][] Start ={
{ 5,4,0 },
{ 6,1,8 },
{ 7,3,2 }};
public static int [][] Goal = {
{ 1,2,3 },
{ 8,0,4 },
{ 7,6,5 }};
I have found where the 0 is and using the outline of the Greedy search, I am moving the tiles in such a vay that It brings the tiles nearer to its goal state. I am moving the Zero and saving the two new Temporary arrays. I now need to run the two arrays through the Manhatten Distance function to find out which is the best to use and then I am going to save the best choice as my new Start array and keep looping through again and again until I have found my goal state!!
I no its long winded but its the only way I understand!!
My problem is that I can not figure out how to enter the temporary arrays into the Manhattan Function to figure out which is best??
I would greatly appreciate any help!!
Here is my source code --
import java.io.*;
public class Puzzle
public static int [][] tempStart1 = new int[3][3];
public static int [][] tempStart2 = new int[3][3];
public static int [][] Start ={
{ 5,4,0 },
{ 6,1,8 },
{ 7,3,2 }};
public static int [][] Goal = {
{ 1,2,3 },
{ 8,0,4 },
{ 7,6,5 }};
public static int i,j,x,y;
public Puzzle()
public static void main(String [] args)
printArray();
findBlank();
public static void printArray(){
System.out.println("Start State");
for( int i =0; i< 3; i++){
for( int j =0; j< 3; j++){
System.out.print(Start[i][j]);
System.out.println("");
System.out.println("\n");
System.out.println("Goal State");
for( int x =0; x< 3; x++){
for( int y =0; y< 3; y++){
System.out.print(Goal[x][y]);
System.out.println("");
public static void findBlank(){
for( int i =0; i< 3; i++){
for( int j =0; j< 3; j++){
if ( Start[i][j] == 0){
System.out.println("\n");
System.out.println("Blank Tile Found at : - ");
if (Start[i][j] == Start[0][0])
System.out.println("0,0");
if (Start[i][j] == Start[0][1])
System.out.println("0,1");
if (Start[i][j] == Start[0][2])
System.out.println("0,2");
swap(Start, 0, 2, 0, 1, 1, 2);
if (Start[i][j] == Start[1][0])
System.out.println("1,0");
if (Start[i][j] == Start[1][1])
System.out.println("1,1");
if (Start[i][j] == Start[1][2])
System.out.println("1,2");
if (Start[i][j] == Start[2][0])
System.out.println("2,0");
if (Start[i][j] == Start[2][1])
System.out.println("2,1");
if (Start[i][j] == Start[2][2])
System.out.println("2,2");
public static void swap( int array[][], int currentPos1, int currentPos2, int FirstMove1, int FirstMove2, int secMove1, int secMove2){
int hold;
int tempCurrNumber1a = currentPos1;
int tempCurrNumber2a = currentPos2;
int tempCurrNumber1b = currentPos1;
int tempCurrNumber2b = currentPos2;
for( int x =0; x< 3; x++){
for( int y =0; y< 3; y++){
tempStart1[x][y] = array[x][y];
tempStart2[x][y] = array[x][y];
hold = tempStart1[tempCurrNumber1a][tempCurrNumber2a];
tempStart1[tempCurrNumber1a][tempCurrNumber2a] = tempStart1[FirstMove1][FirstMove2];
tempStart1[FirstMove1][FirstMove2] = hold;
System.out.print("\n");
for( int x =0; x< 3; x++){
for( int y =0; y< 3; y++){
System.out.print(tempStart1[x][y]);
System.out.println("");
hold = tempStart2[tempCurrNumber1b][tempCurrNumber2b];
tempStart2[tempCurrNumber1b][tempCurrNumber2b] = array[secMove1][secMove2];
tempStart2[secMove1][secMove2] = hold;
System.out.print("\n");
for( int x =0; x< 3; x++){
for( int y =0; y< 3; y++){
System.out.print(tempStart2[x][y]);
System.out.println("");
// Manhatten (|X - X'| + |Y - Y'|).Cross-post:
http://forum.java.sun.com/thread.jsp?forum=54&thread=459075&tstart=0&trange=15 -
How to implement a note on a Java AS(i.e.Enterprise portal)
Hello
How to implement a note on a Java AS(i.e.Enterprise portal)
Thx in advanceHi,
Could you please let us know what kind of note you want to implement on EP ?
Thanks
Sunny -
How to search using java? SearchControl or SearchResult ?
Can anyone help me how to do search in Java? The application i develop is having search field for user.
what do you mean? is it an application with a database? is the user data in the database? then just perform a SQL query like
select * from user_table where name like 'john%' -
How to implement Master-Detail Search in TopLink without using DataControl
Hi,
I am using TopLink and EJB in our requirement. But we are not creating any data controls. Without data controls how to implement master detail search using TopLink and EJB. I did search for a single table. It is working fine. The way i implented is as follows.
1) Taking search parameter from UI and passing it to A delegator class's method.
2) Delegator class's method calls the EJB's NamedQuery which i already created using expression builder.
3) EJB executes the NamedQuery with the parameter we are passing. And it returns the results back to UI.
But as i am new to TopLink, can anyone tell me the procedure to implement Master - Detail search. Here we need to search based on Master table's column.
Waiting for the replies regarding this.
Thanks & Regards,
Suresh KethireddyHi,
I did it successfully. Following is the code.
Session session = getSessionFactory().acquireSession();
UnitOfWork uow = session.acquireUnitOfWork();
ReadAllQuery raq = new ReadAllQuery();
Dept d = new Dept();
d.setLoc(loc);
raq.setExampleObject(d);
List<Dept> res=(List<Dept>)uow.executeQuery(raq);
for(int i=0; i<res.size();i++){
System.out.println("Dept DeptNo ---"+res.get(i).getDeptno());
System.out.println("Dept DeptName ---"+res.get(i).getDname());
System.out.println("Dept Location ---"+res.get(i).getLoc());
List<Emp> eRes=res.get(i).getEmpCollection();
for(int j=0; j<eRes.size();j++){
System.out.println(" Emp No ---"+eRes.get(j).getEmpno());
System.out.println(" Emp Name ---"+eRes.get(j).getEname());
System.out.println("Emp HireDate ---"+eRes.get(j).getHiredate());
System.out.println(" Emp Job ---"+eRes.get(j).getJob());
System.out.println(" Emp Mgr ---"+eRes.get(j).getMgr());
System.out.println(" Emp Sal ---"+eRes.get(j).getSal());
But now my question is, i want to search by providing Dept param as well Emp(Which is child table) param also. Is it possible?
I tried in 2 ways like this.
1) Emp emp = new Emp();
emp.setEname(eName);
dept.addEmp(emp);
raq.setExampleObject(dept);
2) Emp e = new Emp();
e.setEname("ADAMS");
List<Emp> list = new ArrayList();
list.add(e);
d.setEmpCollection(list);
raq.setExampleObject(d);
But in both cases i failed to search based on the values i am passing to Emp.
Is there any other way to achieve my requirement?
Any help on this is great.
Thanks & Regards,
Suresh K -
Implementing n-tier Architecture using java
Hi !!
I wish to know how I can proceed to implement n-tier application using java
or how to implement n-tier application with JBuilder.
Thanks!Easypublic class nTier {
public static void main(String[] args) {
int n =5;
for (int i=0; i<n; i++) {
System.out.println(i + " tier");
}Ted. -
Can we Implement TREX for searching of PO in SRM?
Hello Experts,
Can we implement TREX for searching of purchase order in SRM portal?
I dont want to use SAP NW Enterprise search 7.2 tool using which we can directly search B.O. in SRM.
I want to implement it using TREX in SRM portal.yes this can be done !
check POWL customizing in IMG. -- set TREX based search for feeder type
The documents have to be indexed in TREX for the full-text search to work.
The TREX Search Engine is delivered with SAP SRM, but you must first install it and run program BBP_TREX_INDEX_ADMIN. This program creates a new index for existing documents and enables all new or changed documents to be indexed automatically
hth
thanks
-Adrivit -
How to implement dependencies between search criteria in a Search page
Hi All,
I am using Jdev 11.1.1.6
Someone please let me know how to implement dependency between the search criteria in a search page.
i have found few articles for implementing the same in forms.
i am trying to implement dependencies between search criteria's. i will be using two serach criteria's as lov's in Search page(Using search panel) not in simple forms.
the second criteria lov should be listing all the results based on the firstr search criteria.
someone pls let me know how too implement this.
Regards
SivaThanks Timo,
I got the result. On the dependent attbute properties,i selected the parent attribute and then followed the link for further proceeding.
Its working fine.
Thanks alot for the reply.
Regards
Siva -
How to do exact word search using Java API
Hi,
Can someone tell me how can I write a search query using Ultra Search Java API to return data containing a full word that is sent as a search
parameter. e.g. If I want to search for a word 'Dictionary' I need to get all the results conatining full word Dictionary for example if I
have following 4 records
1. Dictionary
2. English Dictionary
3. French Dictionary
4. AllDictionary
How can I write a query that returns me first 3 records only as they contain the word 'Dictionary' and not the fourth record as it's not a word.
Here is what I need to get back and ordered in that way as the 'Dictionary' needs to be first record because the search is on Dictionary.
1. Dictionary
2. English Dictionary
3. French Dictionary
Any help is appreciated.
ThanksLooks like we can not do an exact word search using Java API.
-
How to search inside java code?
How to search for pattern in Java code from NWDS? For example, I want to search for "wdThis" in java code. Where to look for find or search button?
Hi,
You can also use CTRL+H key for searching any Java or non-Java code across all projects you have opened in your workspace.
Just go to Project Explorer View and select any project, then press CTRL+H, a set of search option will show up.
Hope it helps.
Best regards,
David. -
Implementing circular-left shift in java
i'm an fresher currently in a project on SHA algorithm
i would like to know how to implement circular left shift in java
whether there is any method in java to implement this ,
if in case what package i have to import.
please reply me,
yours sincerely
hari hara ganesh.d
indiaint number= ...;
int shift= ...;
int rotleft= (number<<shift)|(number>>>32-shift);kind regards,
Jos -
Incremental search in java files
Hi,
i m supposed to write an application for Incremental Search in the Java Files.
it is such that, u type a word, then go on hitting any spl key as F3..it should take u to the every next occurance of the word in the current file and highlight it....
any one who has done b4, doing or knows abt this ......
plzzzz hlp me..
thanx in adv
SKHi,
Just giving you an idea to solve this, but implementation of this depends on your hardwork.
We can use Threads concept here. Use a integer variable, which is a global and is used later.
Now TWO java threads are activated.
One of the thread will constantly pool the Standard Input device for desired key value. Once it gets the desired key press value it will increment the integer variable.
The Second thread will serve as the searching thread. This will contantly check the value of the integer variable and the search string variable. If the integer value is more than 0, then this thread will run a methos which will point to the next occurance of the search word. After this it will decrement the value of the integer variable.
You may need to use Synchronization concept also in this when it comes to integer variable.
Hope this idea helps.
Do let me know once u implement the solution.
Cheers. -
Hi,
I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
Phonebook class:
=============
import java.util.*;
public class Phonebook
private static long comparisons = 0;
private static long exchanges = 0;
public static void main (String[] args)
// Create an array of Phonebook records
PhoneRecord[] records = new PhoneRecord[10];
records[0] = new PhoneRecord("Smith","Bob", 1234367);
records[1] = new PhoneRecord("Jones","Will", 1234548);
records[2] = new PhoneRecord("Johnson","Frank", 1234569);
records[3] = new PhoneRecord("Mc John","Pete", 1234560);
records[4] = new PhoneRecord("OBrien","Frank", 1234571);
records[5] = new PhoneRecord("OConnor","Joe", 1234572);
records[6] = new PhoneRecord("Bloggs","Ricky", 1233570);
records[7] = new PhoneRecord("empty","empty", 8888888);
records[8] = new PhoneRecord("empty","empty", 9999999);
records[9] = new PhoneRecord("Van Vliet","Margreet", 1244570);
// call menu
Menu(records);
} // end main
//================================================
// menu
//================================================
static void Menu(PhoneRecord[] records)
int option;
// menu options
System.out.println("===========Menu==============================");
System.out.println("=============================================");
System.out.println(" ");
System.out.println("1. Find record (Advanced Search) ");
System.out.println("2. Quick Search ");
System.out.println("3. Add a record ");
System.out.println("4. Show database ");
System.out.println("5. Sort database ");
System.out.println("6. Exit ");
System.out.println(" ");
System.out.println("=============================================");
System.out.println("=============================================");
System.out.println(" ");
System.out.println("Choose a number ");
option = Console.readInt();
// every menu option has its own method
if (option == 1)
FindRecord(records);
if (option == 2)
QuickSearch(records);
else if (option == 3)
AddRecord(records);
else if (option == 4)
ShowDatabase(records);
else if (option == 5)
quickSort(records, 0, 9);
ShowDatabase(records);
// if 6 then terminate the program
else
System.out.println("Goodbye!");
} // end of menu
//=================================================
// menu option 1: Find a record - using linear search
//=================================================
static void FindRecord(PhoneRecord[] records)
int option;
do
// the user can search based on first name or last name
System.out.println("Do you want to search for:");
System.out.println("1. First Name");
System.out.println("2. Last Name");
System.out.println("3. End search");
option = Console.readInt();
// option 1 is search based on first name
if (option == 1)
System.out.println("Enter First Name");
String first = Console.readString();
int notthere = -1;
for (int i=0; i < 10; i++)
if (first.equals(records.first_Name))
System.out.println("----------------------------------");
System.out.println(records[i].last_Name + ", " + records[i].first_Name);
System.out.println(records[i].phonenumber);
System.out.println("----------------------------------\n\n");
// if a record is found, the variable notthere will be > -1
notthere = i;
} // end search array
// if notthere is -1, then there is no record available
if (notthere < 0)
System.out.println("------------------------------");
System.out.println("No record available");
System.out.println("------------------------------\n\n");
} // end option 1 First Name
// option 2 allows the user to search based on last name
else if (option == 2)
System.out.println("Enter Last Name");
String last = Console.readString();
int notthere = -1;
for (int i=0; i < 10; i++)
if (last.equals(records[i].last_Name))
System.out.println("----------------------------------");
System.out.println(records[i].last_Name + ", " + records[i].first_Name);
System.out.println(records[i].phonenumber);
System.out.println("----------------------------------\n\n");
notthere = i;
// if notthere is -1 then there is no record available
// if notthere is > -1 then there is a record available
} // end search array
if (notthere < 0)
System.out.println("------------------------------");
System.out.println("No record available");
System.out.println("------------------------------\n\n");
} // end option 2 Last Name
else
// if the user types in a wrong number, he or she returns to the menu
Menu(records);
while (option != 3);
} // end FindRecord
//=================================================
// menu option 2: Quick Search - using binary search
//=================================================
static void QuickSearch(PhoneRecord[] records)
// Sort array - Using Quicksort
quickSort(records, 0, 9);
// allow user to enter the last name
System.out.println("Enter Last Name");
String last = Console.readString();
// use binary search to find the target
int index = binarySearch(records, last);
// -1 means that there are no records
if (index == -1)
System.out.println("------------------------------");
System.out.println("No record available");
System.out.println("------------------------------\n\n");
// print out the record
System.out.println("----------------------------------");
System.out.println(records[index].last_Name + ", " + records[index].first_Name);
System.out.println(records[index].phonenumber);
System.out.println("----------------------------------\n\n");
// return to menu
Menu(records);
} // end QuickSearch
public static int binarySearch( Comparable [ ] a, Comparable x )
int low = 0;
int high = 9;
int mid;
while( low <= high )
mid = ( low + high ) / 2;
if( a[ mid ].compareTo( x ) < 0 )
low = mid + 1;
else if( a[ mid ].compareTo( x ) > 0 )
high = mid - 1;
else
return mid;
return -1; // not found
//=================================================
// menu option 3: Add a record
//=================================================
static void AddRecord(PhoneRecord[] records)
int option;
int index = 0;
// enter details
do
// to say that the array is not full yet, I use the variable filled
int filled = 0;
System.out.println("Enter the First Name");
String frst = Console.readString();
System.out.println("Enter the Last Name");
String lst = Console.readString();
System.out.println("Enter the phone number");
int phn = Console.readInt();
// search the array for the empty slot
for (int i=0; i < 10; i++)
if (records[i].first_Name.equals("empty") && filled == 0)
records[i].first_Name = frst;
records[i].last_Name = lst;
records[i].phonenumber = phn;
filled = 1;
// Sort array - Using Quicksort
quickSort(records, 0, 9);
// Print out sorted values
for(int i = 0; i < records.length; i++)
System.out.println("----------------------------------");
System.out.println(records[i].last_Name + ", " + records[i].first_Name);
System.out.println(records[i].phonenumber);
System.out.println("----------------------------------\n\n");
System.out.println("Do you want to add more records?");
System.out.println("1. Yes");
System.out.println("2. No");
option = Console.readInt();
if (option == 2)
Menu(records);
// sets the database to full
int empty = 0;
for (int i=0; i < 10; i++)
// empty = 1 means that there is an empty slot
if (records[i].first_Name.equals("empty"))
empty = 1;
// if the system didn't find an empty slot, the database must be full
if (empty == 0)
System.out.println("Database is full");
option = 2;
Menu(records);
while (option != 2);
} // end AddRecord
//=================================================
// menu option 4: Show database
//=================================================
static void ShowDatabase(PhoneRecord[] records)
// shows the entire database
for (int i=0; i < 10; i++)
System.out.println("----------------------------------");
System.out.println(records[i].last_Name + ", " + records[i].first_Name);
System.out.println(records[i].phonenumber);
System.out.println("----------------------------------");
Menu(records);
//===============================================
// Sort array
//=============================================
public static void quickSort (Comparable[] a, int left, int right)
// Sort a[left?right] into ascending order.
if (left < right) {
int p = partition(a, left, right);
quickSort(a, left, p-1);
quickSort(a, p+1, right);
static int partition (Comparable[] a, int left, int right)
// Partition a[left?right] such that
// a[left?p-1] are all less than or equal to a[p], and
// a[p+1?right] are all greater than or equal to a[p].
// Return p.
Comparable pivot = a[left];
int p = left;
for (int r = left+1; r <= right; r++) {
int comp = a[r].compareTo(pivot);
if (comp < 0) {
a[p] = a[r]; a[r] = a[p+1];
a[p+1] = pivot; p++; }
return p;
} // end class PhoneBook
PhoneRecord class:
================
public class PhoneRecord implements Comparable
public int phonenumber;
public String last_Name;
public String first_Name;
public PhoneRecord(String last_Name, String first_Name, int phonenumber)
this.last_Name = last_Name;
this.phonenumber = phonenumber;
this.first_Name = first_Name;
/* Overload compareTo method */
public int compareTo(Object obj)
PhoneRecord tmp = (PhoneRecord)obj;
// sorting based on last name
String string1 = this.last_Name;
String string2 = tmp.last_Name;
int result = string1.compareTo(string2);
if(result < 0)
/* instance lt received */
return -1;
else if(result > 0)
/* instance gt received */
return 1;
/* instance == received */
return 0;JosAH wrote:
prometheuzz wrote:
bats wrote:
Hi,
I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
...Looking at your binary search method:
public static int binarySearch( Comparable [ ] a, Comparable x)I see it expects to be fed Comparable objects. So, whatever you're feeding it, it's not a Comparable (ie: it doesn't implement Comparable), hence the CCE.It's even worse: if an A is a B it doesn't make an A[] a B[].
kind regards,
JosMy post didn't make much sense: if there were no Comparables provided as an argument, it would have thrown a compile time error. The problem lies in the compareTo(...) method. -
How to implement logging functonolity in my java application
Hi.
I want to add logging functionality in my java project.Iam using jdk1.5.I have written following log4j.properties.This property file i need to keep it in com.format.src.property folder .All java files are there in com.format.src folder.
log4j.rootCategory=DEBUG, FILE, CONSOLE
### A bootstrap file appender
log4j.appender.FILE=org.jboss.logging.appender.FileAppender
log4j.appender.FILE.File=${jboss.server.log.dir}/${HOSTSHORTNAME}-${jboss.server.name}-boot.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n
log4j.appender.FILE.Append=false
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n
Could you reply me the steps to implement logging in my project.
Thanks in advance
alex1) Put the Apache Commons Logging jar into your "lib" folder.
2) Create your properties file as "log4j.properties"
3) Keep it inside the folder where you have your "src" (ie. ur "src", "classes", & "log4j.properties" should be in the same folder)
4) Import "org.apache.log4j.Logger;"
5) Create an instance of "Logger" as follows;
Logger log = Logger.getLogger(YourClassName.class.getName());
6) Use the created "log" instance when applicable as follows:
log.info("Whatever the message");
log.debug("Whatever the message");
log.error("Whatever the message");
log.fatal("Whatever the message"); ...etc
Hope u got it... Happy coding... :)
Cheers,
Asela.
Maybe you are looking for
-
Using an external image file to display on page while page is loading
I am uploading my site to a host that insists that I put their logo on the top of my web pages. They will not permit me to embed the logo on the page. They want me to insert an image srch on the page to a graphic file they store locally. This is so t
-
Line wraping only selected text in JTextPane
Is it possible to not word wrap styled text word groups in JTextPane so that the word groups are kept together. I would have liked to do this with by adding a 'keep together' attrib. to StyleConstants in my StyledDocument but sadly this is not possib
-
NotifyIcon icon still visible after closing form
Hi, I have an application that's using NotifyIcon control. Everything is fine except when I exit the application, the icon is still in the "system tray" area. I want it to disappear once I exit the application. Anyone have the same experience, pls sh
-
Directory selection in external table
How do we select the directory path for external table files?.whether we can select any directory in any drive or we have to select particular drive and particular directory path?.how do we check for this?. example create or replace directory ext_dir
-
How to compress aggregate only
Hi we have process chain which got failed because of activation of ods. I done it manually and this ODS is updates further two cube. Both Cube is having setting "compress after Rollup" as we are only compressing aggregates of those cubes . After Fu