I got 5 columns in a table: Name, Birth year, Gender, Occupation and Salary.
Task is to check whether occupation column title is located
at 2nd place from the right side.
public void positionofOccupation() {
List <WebElement> ch = driver.findElements(By.xpath("//button[#class='header']"));
for (int i = ch.size(); i > 0; i--) {
WebElement ch1 = driver.findElement(By.xpath("(//button[#class='header'])[" + i + "]");
if (ch1.getText().trim().contains("Occupation")) {
System.out.println("Occupation position is at " + i + " column);
}
else {
System.out.println("Occupation position is wrong and is at " + i + " column);
}
}
}
It's printing me a 4 instead of 2 when that "if" condition is true. I need to print 2 because test case is about 2nd position not 4th position.
The code is working exactly as written. The desired text is found in the 4th column, not the second. You are decrementing the column counter from the max column, for (int i = ch.size(); i > 0; i--), but not subtracting the found column index from the max column index if you want to find the position from the rightmost column.
I think what you are looking for is
public void positionofOccupation() {
List<WebElement> ch = driver.findElements(By.xpath("//button[#class='header']"));
for (int i = ch.size(); i > 0; i--) {
WebElement ch1 = driver.findElement(By.xpath("(//button[#class='header'])[" + i + "]"));
if (ch1.getText().trim().contains("Occupation")) {
Integer columnFromRight = ch.size() - i + 1;
System.out.println("Occupation position is " + columnFromRight + " columns from the right");
} else {
System.out.println("Occupation position is wrong and is at " + i + " column");
}
}
}
Rather than using sysout prints to the log, I would suggest you investigate JUnit, TestNG, or some other assert library. It will make your work much easier. Your if else and sysout messages will turn into just
assertEquals(2, columnFromRight, "Verify 'Occupation' column is second from right");
...and you'll get a report of what tests passed/failed rather than having to look through all the logs.
Related
I have the following code, and I would like the user inputs to store, and then the code loop back with the next input storing also, until they hit "Q" which will then quit. I am not sure how to do it.
Also, I want my 2d array to be printed blank, instead of the default 0s, after the user sets the size. SO if the user says they want to input SIZE = 4x4 "row =1, column =2, input =7" it would print "These ZEROS would be BLANK
0000
0070
0000
0000
the input "row 2, column 1, input A it would print
0000
0070
0700
0000
My code so far
import java.util.*;
public class MainProg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many rows do you want for your matrix? ");
int row = in.nextInt();
System.out.print("How many columns do you want for your matrix? ");
int column = in.nextInt();
String[][] newArray = new String[row][column];
Array2 twoDArray = new Array2(row, column, newArray); //calling my class
do {
System.out.println("If you would like to set an, element press S: " + "\n" +
"If you would like to set an element, press G" + "\n" +
"If you would like to empty an element, press E" + "\n" +
"If you would like to print an element, press P" + "\n" +
"If you would like to quit, press Q");
String userInput = in.next();
if (userInput.equalsIgnoreCase("S")) {
twoDArray.setElement();
} else if (userInput.equalsIgnoreCase("G")) {
twoDArray.getElement();
} else if (userInput.equalsIgnoreCase("E")) {
twoDArray.clearElement();
} else if (userInput.equalsIgnoreCase("P")) {
twoDArray.printMatrix();
//you will do you toString here
} else if (userInput.equalsIgnoreCase("Q")) {
//this will quit the program
twoDArray.quitProgram();
}
//break;
} while (true);
}
}
import java.util.*;
public class Array2 {
MainProg main1 = new MainProg();
Scanner in = new Scanner(System.in);
private String [][] newArray;
private int row;
private int column;
public Array2(int row, int column, String[][] newArray) {
this.row = row;
this.column = column;
this.newArray = newArray;
}
public void getElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like to get in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to get in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
String getElement = newArray[userRow-1][userCol-1];
System.out.println(getElement);
}
public void setElement() {
System.out.println("What row would you like your element in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column would you like your element in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("What character would you like the element to be?");
String userChar = in.next();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[userRow][userCol] = String.valueOf(userChar);
}
public void clearElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like empty? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to empty? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
}
public void printMatrix() {
Scanner in = new Scanner(System.in);
//String result = " ";
System.out.println("The array is: \n");
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) {
System.out.print(newArray[i][j]);
}
//for (String[] row: newArray) THIS LEAD TO A PROBLEM
// Arrays.fill(row, " ");
System.out.println();
}
}
public void quitProgram() {
System.out.println("The system will now exit! BYE!!!");
System.exit(0);
}
}
I have EDITED my code so that I have answered some questions. Now my only problem left is getting my matrix to be initially filled with blanks " ", instead of the default "null". I attempted to use the Arrays.fill in my printMatrix method, however that lead to problems, it would not save the user input after the loop.
Your IndexOutOfBoundsException (now editted out) is due to you using row and column instead of userRow and userColumn in setElement, which are where you've stored the user inputs. row and column will refer to the classes member variables, which are both 5 since you set it up as a 5x5 matrix, so above the max index of 4. You also will need to conver the char to a string since your using a String[][]
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[row][column] = userChar;
The last line should be newArray[userRow][userColumn] = String.valueOf(userChar);. Though you probably want to check those values are less than row and column to avoid more of that exception.
Even with that fixed, your code currently has other issues. The biggest is that you're currently defininig and using a new array in most methods and not the member variable newArray, so the method calls to get/set/clear/print aren't using your instance like you expect, but new empty arrays each time. These should be manipulating this.newArray not creating their own to manipulate, which dies with their return. You'll need to work through fixing all of that before looking into looping over the user input and interacting with your array.
On the printing of 0's, that is a side affect of one of the above issues. In printMatrix you declare a new int[][] newArray and print that. The default value of int is 0, so you get all 0's. If you were using your String array you'd get all "nullnullnull.." for each row as String's default to null. If you want all blanks initially, you'll have to initalize the array to all empty strings in your constructor or handle the null when looping through the array printing a space instead.
On looping for user input, you'll also need to ask for it again inside of your loop before the while, as otherwise the user input will only be asked for once and you will forever loop with that option.
Good luck, this seems like a good excersize to familiarize yourself with OO and array maniupulation, but a lot of the issues in your code are outside the scope of a single SO answer and smells a bit like classwork. I got your example code fixed up and manipulating as you want with only a handful of changes, so youre close.
EDIT:
In the future, please don't continuously edit questions to reflect further development unless you leave the original in place and add to it and it still reflects a continuation of the original problem, as it makes answers and comments have no context. SO is meant more to be questions and answers about specific issues faced, not a forum for feedback on continued development. If you got past a specific problem via an answer, mark that answer as the solution and move any new issues into a new question, else you risk having your question closed. See the first few topics under https://stackoverflow.com/help/asking, especially https://stackoverflow.com/help/how-to-ask, to see what I mean. I'm being pretty gentle, but this community can not always be.
That being said, as you seem to be making a geniune effort here, here's a few more bits of advice based on your comments and edits.
If you want to prefill the rows with spaces, the
for (String[] row : newArray)
Arrays.fill(row, " ");
block of code would not go in print, as that would blank it out each time print is called. It should go into your constructor, so that it only happens once when the object is created.
Alternatively, if you wanted to deal with it in the print method, something like
System.out.print(newArray[i][j] == null ? " " : newArray[i][j]);
Would do the trick, using a ternary operator to print out " " instead of null when encountered.
You also don't need to new up the Scanner in those methods but its not affecting functionality.
I haven't coded in Java for a long time and during the lockdown working on getting back into it. I have this puzzle I've come across and wondering if someone can help me with it:
1). Split the given string into the size of the given int
2). return how many times the string would need to be split for the given int
3). no splitting words
String random = "I want to take this and only send it at a certain number";
int random_number =12;
public int splitTheString (String random, int random_number) {
int total = 0;
int counter = 0;
String [] str = random.split(" ");
for(int i=0; i<str.length;i++)
{
total += str[i].length();
if(total < random_number){
System.out.println(str[i] + " less than 12");
counter ++;
} else {
System.out.println(str[i] + " More than 12");
counter ++;
}
System.out.println(total + " " + counter);
return counter;
}
}
So from main the method would be called: splitTheString (random, random_number)
I'm trying something like the above but think Im headed in the wrong direction. Can someone help out. Thanks
Edit:
Expected input:
Strings:
1). "Messages won't be too long"
2). "These messages are great"
3). "Random messages are fun to play with"
4). "Some won't be words like kkkk lllll pppp llll"
5). "All these will be the kinds of inputs"
Expected outputs, can be split:
1). "Messages", "won't be too", "long" => 3
2). "These", "messages are", "great" => 3
3). "Random", "messages are", "fun to play", "with" => 4
4). "Some won't be", "words like", "kkkk lllll", "pppp llll" => 4
5). "All these will", "be the kinds of", "inputs" =>
First of all, DEBUG your code, follow the changes of the variables value on every iteration, I am sure you can see where the things start going wrong.
Beloved is just an example, start with
static int splitter(String fullSentence, int maxChar) {
do string-split as you did, define two variables, one for count like yours, other for the current split word(s),
String split = "";
int count = 0;
iterate the words of full sentence,
for (int i = 0; i < words.length; i++) {
check if split + words[i] 's length is less than the maxChar, do not forget to add 1 for blank between the words,
// check if words[i] is blank or empty!!!
if (split.concat(words[i]).length() + 1 <= maxChar) {
split = split.length() == 0 ? words[i] : split.concat(" " + words[i]);
}
else {
// we reached max possible chars
if (split.length() > 0) {
System.out.print(split + ", ");
count++;
}
split = words[i];
}
when you finished the iteration, check again if split words has some value, even check if it includes last word of full sentence then report it and increase the count if necessary
System.out.println(" => " + count);
end return the count;
return count;
So in my application I am trying to iterate through my rs records. I want to be able to print out a ranch of records at a time so like if I have 100 records and records 3, 12-15 and 40-60 are missing, I want it to display the records that was read. So I can know that the other records are missing/skipped. I have posted a more completed code here Java JDBC display first 500 records at a time, commit, than display the next 500 records and etc
updated records 1-2
updated records 4-11
updated records 13-39
updated records 61-100
try {
int rowCount = 0;
while (rs.next()) {
String ingressflag = rs.getString("ingress_flag");
String egressflag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
int profileid = rs.getInt("profile_id");
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setInt(5, profileid);
preparedStatement.addBatch();
rowCount++;
// System.out.println("profileid updated : " + profileid + " timestamp " + new java.util.Date() + "\n");
}
If you want to find which profile_id is missing you could try to declare a variable of type int say expectedId and initialise to the starting profile_id of the table in your case 1. Then in the while loop check whether the profile_id returned is equal to the expectedId if not print out the message and finally increment the expectedId by 1 as Illustrated below.
int expectedId = 1;
while (rs.next()) {
//All your code
if(expectedId != profileid){
System.out.println ("Profile id "+expectedId+" to "+(profileid-1)+" missing.";
expectedId = profileid;
}
expectedId++;
}
Here whenever the sequence is missing it will give an output stating the id from which to which are missing.
I would use an array of booleans that is the same size as the number of records your have. Then set each corresponding value to True if and only if that record was updated.
Then from this array you can give output in the form you suggested by simply looping through the array with something like:
int first;
int last = 0;
while(!records[last]) //skip through records 1-x that are missing
last++;
first = last+1;
for(int i = last; i < numRecords; i++){
if(records[i]) //keep going if record there
last++;
else{ //otherwise print out previous "streak" and start anew
if(first == last) //streak of 1
System.out.println("updated record " + first);
else //streak of >1
System.out.println("updated records " + first + "-" + last);
while(!records[i]) //skip over entire missing section
i++;
first = i+1; //new first is next valid value
last = first;
}
}
if(records[numRecords-1])//if end reached without printing last streak
System.out.println("updated records " + first + "-" + last); //print it now
I am making a horse race program that will print the 1st 2nd and 3rd place horses. I have to set up the 10 horses in an array and then add random number from 1-3 to their position. The winner is the first horse to hit 15 or beyond.
My problem is that my program does not properly print the 2nd and 3rd place horses.
[UPDATE] I removed the many conditions and added string variables to store the information. It runs smoother but now I dont know why the program keeps printing duplicates and such.
Here is the code, I updated the for loop that was printing the winners:
import java.util.*;
public class HorseRace{
public static void main(String[ ] arg){
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 5;
Random ran = new Random( );
boolean winner = false;
boolean second = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(winner!=true){//loop forever until winner
//begin program
System.out.print(readString);
if(readString.equals("")){//when enter is pressed
for(int i = 0; i<arrRan.length; i++){//loop that adds position when enter is pressed
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1); //add to the array in random numbers
System.out.println("Horse " + (i+1) + ": " + arrRan[i]);//print the contents of the array
}
}//end if
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter.");
}
for(int i = 0; i<arrRan.length; i++){
if(arrRan[i]>=15){//if a winner is found
first = first + "Horse " + (i+1)+" ";
winner = true;
}
//if winner is found then look for a 2nd place
//if there is no position 14 then search for 13, if no 13 then 12. The lowest 2nd place will be in position 12.
if(arrRan[i]==14){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=14&&arrRan[i]==13){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=13&&arrRan[i]==12){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]==13){
third = third + "Horse " + (i+1)+" ";
}
}
if(winner==true){
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}//end while
}//close main
}//close class
You can exit from a for loop using the break statement.
You can search for the three best horses by looping through all horses and saving the best ones on the fly. After that you print the result.
Have three variables for the numbers of the three best horses, and three variables for the distance of the three best horses.
In the loop, you check whether the horse you are currently looking at is better than the first, second or third horse. Then you insert it at the corresponding place and shift the other horses down.
At the end, you will have the three best horses with their distance, and can just print them one by one.
Shifting down can be implemented Mike this:
int horse1, horse2, horse3, d1, d2, d3;
// Do something...
horse3 = horse2;
d3 = d2;
horse2 = horseNew;
d2 = dNew;
You should be able to figure out the shifts when inserting at place one and three.
Instead of your for loop that checks the winners from first to third place, you can use this: So if there is a winner, the while loop comes out.
winner = checkAndPrintWinner(arrRan);
And then to find the winners itself, the below code does sorting to see if there is a winner and if there is, it keeps track of last value so it can do an append or add to new element in the winners array. Feel free the print the results in a different way. The code could be optimized a bit more.
private static boolean checkAndPrintWinner(int [] data) {
boolean isWinner = false;
// Do copy and then Ascending sort
int results[] = Arrays.copyOf(data, data.length);
Arrays.sort(results);
if (results[results.length-1] >= 15) {
// We have a winner
isWinner = true;
String winners[] = new String[3]; // First three winners
winners[0] = ""; winners[1] = ""; winners[2] = "";
int index = 0;
int total = results.length;
int lastValue = results[total-1];
int fromIndex = 0;
// Start from the back of sorted array where our winners are.
for (int i = total-1; i >= 0; i--) {
int nextValue = results[i];
// if values differ, move on to next winner
if (lastValue != nextValue) {
fromIndex = 0;
index++;
}
// we got all three winners, so break
if (index == 3) break;
// Get the next winning index
fromIndex = getHorseIndexForValue(fromIndex, nextValue, data);
winners[index] += " Horse " + (fromIndex + 1);
lastValue = nextValue;
// If winning values are same, next time we want to search from the last found index(fromIndex) + 1.
fromIndex++;
}
System.out.println("Winners: " + Arrays.toString(winners));
}
return isWinner;
}
// Get where our horse is based on its score
private static int getHorseIndexForValue(int from, int value, int [] data) {
for (int i = from; i < data.length; i++) {
if (data[i] == value) {
return i;
}
}
return -1; // should never come here
}
Your logic seems to have many flaws.
while loop doesn't seem to end
first to reach 14 may not be the first
to reach 15, so you should make sure that no duplicate values are
present in first, second and third first,
once set should not be set again
while loop should break once all three are found.
Use break statement to exit the loop
UPDATE :
Lets assume, horse1 is the only one to reach on or beyond 13. In that case,
1. IN any iteration, Horse1 = 13, then first = null, second=Horse1, third = Horse1
2. Horse1 = 14, first = null, second=Horse1, third = horse1
3. Horse1 = 15, first = horse1, second = Horse1, third = Horse1
In the above example, no variable is being re-set to another value as no other horse has reached to a value of 12 or beyond
Hence, possibility of duplicates
Let me know if I got it right
for(int i = 0; i<arrRan.length; i++){
if(arrRan[i]>=15){//if a winner is found
first = first + "Horse " + (i+1)+" ";
winner = true;
}
//if winner is found then look for a 2nd place
//if there is no position 14 then search for 13, if no 13 then 12. The lowest 2nd place will be in position 12.
if(arrRan[i]==14){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=14&&arrRan[i]==13){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=13&&arrRan[i]==12){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]==13){
third = third + "Horse " + (i+1)+" ";
}
}
I am writing a program that takes a document created by one program by PrinterWriter and then hashes the lines in that document to an array in the new program. The hash is done by using the ASCII code for the letter and adding them up. I am able to get the correct hash for each line and save it in the hash table. By the way, it is a list of countries that is hashed. My problem is that it does not seem to be able to compare the countries entered by the user, even though it is copy and paste, to the ones in the hash table to display them. It is not only supposed to display the country in the hash table, but all the ones leading up to the hash table. So if one was supposed to go to spot 23 but went to spot 26, display 23-26 to show clustering. I have tired everything to get it to work, but nothing seems to work, please help. I have included some of the code:
import java.io.PrintWriter;
import java.io.File;
import java.util.*;
import java.text.*;
public class Hashing
{
String[] line = new String[238];
String[] HashTable = new String[300];
public Hash() {
for (int i = 0; i< HashTable.length; i++) {
HashTable[i]=null;
}
}
public void readIn()throws Exception {
Scanner ln = new Scanner(new File(System.getProperty("user.home"), "user.home.CountryUnSortedFormat.txt"));
int i = 0;
while (ln.hasNextLine()) {
line[i] = ln.nextLine();
i++;
}
}
public int toASCII(String input) {
int total = 0;
char character;
String str = input.replaceAll(",","").trim();
if (str.length() > 50) {
for (int i = 0; i<50; i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
} else if (str.length()<50) {
for (int i = 0; i<str.length(); i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
}
return total % 300;
}
public void hashIt(String input, int where){
int counter = where;
if (where==299 && HashTable[where]!=null){
counter = 0;
}
while (HashTable[counter]!=null){
counter++;
}
System.out.println("Country = " + input + " HashValue = " + where + " actual HashSpot = " + counter);
HashTable[counter]=input;
}
public boolean showCountries(String paramCountry, int where){
int location = where;
int length = paramCountry.length();
while (!(HashTable[location].substring(0,length).contains(paramCountry))){
System.out.println("Input = " + paramCountry + " and HashTableCOunty = " + HashTable[location].substring(0,length));
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
if (!(HashTable[location].substring(0,length).contains(paramCountry))){
location++;
}
else if (HashTable[location].substring(0,length).contains(paramCountry)){
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
System.out.println("Eguals");
return true;
}
if (location==300||HashTable[location]==null){
System.out.println("End");
return false;
}
}
return false;
}
public void displayHashTable() {
for (int i = 0; i<HashTable.length; i++) {
System.out.println("i = " + i + " " + HashTable[i]);
}
}
public static void main(String[]args)throws Exception {
Scanner kb = new Scanner(System.in);
Hash H = new Hash();
H.readIn();
for (int i = 0; i< 238; i++) {
int where = H.toASCII(H.line[i]);
H.hashIt(H.line[i], where);
}
H.displayHashTable();
String UserChoice;
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
while (!(UserChoice.equalsIgnoreCase("-1"))) {
int index = H.toASCII(UserChoice);
boolean error = H.showCountries(UserChoice, index);
while (error == false) {
System.out.println("The country you searched for is not in the hash table. Try again.");
UserChoice = kb.nextLine();
index = H.toASCII(UserChoice);
error = H.showCountries(UserChoice, index);
}
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
}
}
}
Let us look at showCountries method:
public boolean showCountries(String paramCountry, int where) {
//....
return false;
}
I removed every line, that does not contain a return statement. As you can see, you always return false no matter if the searched element was found or not.
Therefore this loop:
while (error == false) {
//...
}
is like an infinite loop.
Change the code in your showCountries method to return true, it the country was found.
And consider changing the variable name error to something else. error == false sounds like "everything was ok", but this is not the case here.
If I understand your code correctly, you can change this:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
break;
}
to:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
return true;
}
Edit:
Another error-prone point is right here:
int length = paramCountry.length()-1;
while (!(paramCountry.equals(HashTable[location].substring(0,length)))) {
//...
You're cutting off the last character due to the usage of -1.
A small example:
paramCountry = "Eng";
HashTable[0] = "England";
int length = paramCountry.length()-1; // 2 (paramCountry.length() is 3)
And this are the results with the above values:
HashTable[0].substring(0,length)) // "En"
paramCountry.equals(HashTable[0].substring(0, length)) // "Eng".equals("En") -> false
So, you can remove that -1 or get rid of that substring and use contains instead.
Edit 2:
So, after your edit use contains instead of substring you only have one error left (the last one I cuurently see ):
while (!(HashTable[location].substring(0, length).contains(paramCountry))) {
// ...
}
return false;
Before you're calling the method showCountries you're calculating the possible position by calling H.toASCII(UserChoice);. This position is given to the method as location there it is used in the above while loop. This loop will be skipped, because the search country is already found. The bad thing is: you will return false in this case.
Now I suggest to change this return to return true; because this line will only be reached if the searched country was already found (and the while loop was skipped). If the country could not be found, you will return false in this if body: if (location==300||HashTable[location]==null).