Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Thursday, July 16, 2015

Java program to validate the PAN card Number : Regular expression

Write a java program to validate a PAN Card number. A PAN card number is said to be valid when it starts with 5 uppercase letters 4 digits and Followed by single upper case letter. A Valid PAN have only 10 letters.

For example: a pan card number AMEPJ2585B is valid where as AM525LDKF is invalid.

Given below is the java program which makes use of regular expressions to validate the PAN number. 

ValidPan.java


import java.util.*;
class ValidPAN 
{
 public static void main(String[] args) 
 {
  Scanner scn=new Scanner(System.in);
  int t=scn.nextInt();
  String s[]=new String[t];
  boolean output[]=new boolean[t];
  for(int i=0; i<s.length;i++)
  {
   s[i]=scn.next();
   boolean ss=s[i].matches("[A-Z]{5}\\d{4}[A-Z]{1}");
   output[i]=ss;
  }
  for(boolean b:output)
  {
   System.out.println(b);
  }
  
  

 }
}



Sample Output: 





Monday, July 13, 2015

Java program to convert the number in time format


Given below is the java program to print the time given in number format to String format.

For example: if you give input as 5 45, the below program will print Quarter to six


import java.util.*;
class TimeTest 
{
 public static void main(String[] args) 
 {
  String addString="";
  HashMap<Integer,String> hm=new HashMap<Integer,String>();
  hm.put(1,"one");hm.put(2,"two");hm.put(3,"three");hm.put(4,"four");hm.put(5,"five");
  hm.put(6,"six");hm.put(7,"seven");hm.put(8,"eight");hm.put(9,"nine");hm.put(10,"ten");
  hm.put(11,"eleven");hm.put(12,"twelve");hm.put(13,"thirteen");hm.put(14,"forteen");hm.put(15,"fifteen");
  hm.put(16,"sixteen");hm.put(17,"seventeen");hm.put(18,"eighteen");hm.put(19,"ninteen");hm.put(20,"twenty");
  hm.put(21,"twenty one");hm.put(22,"twenty two");hm.put(23,"twenty three");hm.put(24,"twenty four");hm.put(25,"twenty five");
  hm.put(26,"twenty six");hm.put(27,"twenty seven");hm.put(28,"twenty eight");hm.put(29,"twenty nine");hm.put(30,"thirty");

  Scanner scn=new Scanner(System.in);

  int hour=scn.nextInt();
  int minute=scn.nextInt();

  if(minute==00)
  {
   addString=hm.get(hour)+" o' clock";
  }
  else
   if(minute==15)
  {
   addString="quarter past "+hm.get(hour);
  }
  else
   if(minute==30)
  {
   addString="half past "+hm.get(hour);
  }
  else 
   if(minute>30&&minute==45)
  {
   addString="quarter to "+hm.get(hour+1); 
  }
  else
   if(minute>30&&minute!=45)
  {
   minute=60-minute;
   String midString="minute";
   String min=String.valueOf(minute);
   if(min.length()>1)
   {
    midString="minutes";
   }
   addString=hm.get(minute)+" "+midString+" to "+hm.get(hour+1); 
  }
  
  else
  {
   String midString="minute";
   String min=String.valueOf(minute);
   if(min.length()>1)
   {
    midString="minutes";
   }
   
   addString=hm.get(minute)+" "+midString+" past "+hm.get(hour); 
  }

  System.out.println(addString);

 }
}

Sample output

Monday, March 2, 2015

How to access the private method of a class outside of the class in Java. [Reflection]

How to access the private method of a class in other class. For example check the below class Return , it has a private method rate(). How to access method rate() outside of class Return.


package reflection;

public class Return {
 int price, discount;

 private int rate() {
  return (price - discount);
 }
}



Although, private methods are meant to be accessed in the same class they are declared and when we try to access it outside of the declared class it gives a compile time error. But Reflection API of java provides a way to access private method outsides of class. 

Check the below code which access the rate() method of Return class in Test class.


package reflection;

import java.lang.reflect.Method;

class Test {
 public static void main(String[] args) throws Exception {
  Return p = new Return();
  Method m = p.getClass().getDeclaredMethod("rate", null);
  m.setAccessible(true);
  System.out.println(m.invoke(p));
 }
}



Under the hood - no private stuff is actually private.

Thus, the field or method can be accessed.
In byte code - there is a flag which is byte code level implementation of private-ness.

Saturday, February 28, 2015

Write a Java program to print the following pattern. [Interview Question]

Write a Java program to print the following pattern.

1
3*2
4*5*6
10*9*8*7
11*12*13*14*15

Given above is a frequently asked question in interviews from Java developers.


class TrianglePattern 
{
 public static void main(String[] args) 
 {
  int n=15;
  int i=1;
  int cnt=1;
  boolean ltr=true;
  while(i<n)
  {
   String s="";
     if(ltr)
      for(int j=0;j<cnt;j++)
    s=s+(s.length()>0?"*":"")+i++;
     else
     for(int j=0;j<cnt;j++)
    s=i++ +(s.length()>0?"*":"")+s;
     cnt=cnt+1;
     ltr=!ltr;
     System.out.println(s);
  }
  
 }
}


Output:





Friday, February 27, 2015

[Webdriver] Selenium test script to scroll and print all items name from a web page.

Write a selenium web driver test script to scroll and print all items name from a web page. Below is an example using FlipKart.

Scenario

  • Log in to Flipkart.

  • Type Samsung in search box and Click search button.

  • Click mobile link.
  • Scroll and print all the names.


Scrolling is the only challenging portion here, until when we have to scroll is the question. In the above scenario we will scroll the web page until no-more-results are displayed.


package chubJava;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FKart_Test {
 
 static WebDriver driver=new FirefoxDriver();
 
 public static void main(String[] args) {
  driver = new FirefoxDriver();
  driver.get("http://www.flipkart.com");
  driver.findElement(By.id("fk-top-search-box")).sendKeys("Nokia");
  driver.findElement(By.xpath("//form[@id='fk-header-search-form']/div/div/div[2]/input[1]")).click();
  driver.findElement(By.partialLinkText("Mobiles")).click();
  JavascriptExecutor jse = (JavascriptExecutor) driver;
  int count = 1500;
  while (!driver.findElement(By.id("no-more-results")).isDisplayed()) {
   count = count + 500;
   jse.executeScript("scroll(0, " + count + ")");
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   if (driver.findElement(By.id("show-more-results")).isDisplayed()) {
    driver.findElement(By.id("show-more-results")).click();
   }
  }

  List<WebElement> al = driver.findElements(By.xpath("//div[contains(@class,'pu-title')]/a"));

  System.out.println(al.size());

  for (int i = 0; i < al.size(); i++) {
   System.out.println(al.get(i).getText());
  }
  
  driver.close();
 }

}

Ping us for any help. Like us at Facebook.

Monday, December 22, 2014

How to separate words from String in java. Break the String in meaningful sentence.

Problem : Given an input string , separate the input string into a space-separated sequence of dictionary words if possible. For example, if the input string is "helloworld" then we would return the string "hello world" as output.

Assume you are given a Dictionary against which you can check the validity of words. Print "String can not be separated" if it contains numbers , any special character or any invalid combination of character/word.

Solution in java


/**
 * Created by IN00474 on 22-12-2014.
 */

import java.util.*;
public class StringToSentence {

    static List<String> l = new ArrayList<String>();
    static String wordToCheck = "";

    public static void main(String[] args) {
  if (args.length==0)
  {
   System.out.println("Pass the input String");
   System.exit(1);
  }
        String inputString = args[0];
        if (inputString.matches("[a-zA-Z]+")) {
            for (int i = 0; i < inputString.length(); i++) {
                wordToCheck = wordToCheck + inputString.charAt(i);
                if (checkInDictionary(wordToCheck)) {
                    l.add(wordToCheck);
                    wordToCheck = "";
                }
                else
                {
                    if(i==inputString.length()-1)
                    {
                        System.out.println("String can not be sorted");
                        return;
                    }

                }
            }
            displaySentence(l);
        } else {
            System.out.println("String can not be sorted");
        }
    }

    public static boolean checkInDictionary(String wordToCheck) {
        ArrayList al = new ArrayList();
        al.add("hello");
        al.add("world");
        if (al.contains(wordToCheck)) {
            return true;
        } else {
            return false;
        }
    }

    public static void displaySentence(List l) {
        Iterator i = l.iterator();
        while (i.hasNext()) {
            System.out.print((String) i.next() + " ");
        }
    }

}



Please note this code was tested against multiple use cases and return correct results, let us know if any of the use case if fails to pass.


Run time result



Java Program to find missing and repeated number from an unsorted array.

Problem : Given an unsorted array of size n. Array elements are in range from 1 to n.One number from set {1, 2, …n} is missing and one number occurs twice in array. Find these two numbers.



Approach to solve (Algorithm)

1. Sort the input unsorted Array in ascending order.
2. Run a loop from index 0 to length-1;
2. Find the difference between element at i & i+1 index.
if difference==-1 continue the loop;
   else
if(difference==0) //So the Number at i index is repeated 
   else

if(difference==-2)//So the Number at index[i]+1 is missing. 


Thursday, November 27, 2014

TreeSet in java : A detailed overview

TreeSet in java under Collection Framework have below property.

1. Underlying data structure is balanced  tree.
2. Doesn't allow duplicate.
3. Elements are inserted as per natural sorting order by default.
4. All elements which are inserted as per default natural sorting order must be comparable in nature.
5. An object is said to be comparable only if corresponding class implements java.lang.Comparable interface.
6. If we use default natural sorting order than objects are compared using compareTo(Object obj) method of java.lang.Comparable interface.
7. Null insertion is not allowed.


Constructor in TreeSet

TreeSet ts=new TreeSet(); //creates an empty TreeSet with default natural sorting order
TreeSet ts=new TreeSet(Comparator c); //creates an empty TreeSet with passed Customoized sorting order

TreeSet ts=new TreeSet(SortedSet s); //Creates a TreeSet view of a Passed SortedSet argument object.


//TreeSetDemo.java


import java.util.*;
class TreeSetDemo 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet();
  ts.add("10");
  ts.add("20");
  ts.add("30");
  System.out.println(ts);
 }
}



TreeSet by default stores objects which are homogeneous and comparable, an object is said to be comparable if and only if it implements Comparable interface.

TreeSet stores elements based upon the default natural sorting order.Elements in the TreeSet are comparaed using compareTo(Object obj) method of java.lang.Comparable interface.

But if we want to store objects based upon our own customized sorting order then we need to have a class which implements java.util.Comparator interface.


Comparator


  • It is meant for customized sorting order.
  • Present in java.util package.
  • Contains below 2 method.

1. public int compare(Object obj1,Object obj2)
2. equals()


any class which implements java.util.Comparator Interface should compulsory implement compare() method. Whereas implementing equal() method is optional.

This is because every java class is a child class of Java.lang.Object class. Object class provide implementation for equals() method, so equals () is by default present in every java class.


Write a java program to insert Integer elements in TreeSet with desecending sorting order.



import java.util.*;
class ReverseTreeSet 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet(new Com());
  ts.add(10);
  ts.add(20);
  ts.add(30);
  ts.add(40);
  ts.add(50);
  System.out.println(ts);
 }
}

//Java code for customized sorting order


import java.util.*;
class Com implements Comparator
{
 public int compare(Object obj1, Object obj2)
 {
  Integer i1=(Integer)obj1;
  Integer i2=(Integer)obj2;
  return i2.compareTo(i1);
 }
}