Friday, 3 January 2014

Java program to print Palindrome number after number n passed by user.

Write a Java program to print Palindrome number after number n   passed by user.

package programs;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
int num;
System.out.println("Enter number after which Palindrome String u want");
Scanner in = new Scanner(System.in);
num = in.nextInt();
findPalindrome(num);
}

public static void findPalindrome(int number){
for(int x=number+1; ;x++){
boolean flag=checkPalindrome(x);
if(flag==true){
break;
}     else
continue;          
}               }

public static boolean checkPalindrome(int number){
int mod=0;
int temp=0;
int reverse=0;
temp=number;
while(number!=0){

mod=number%10;
reverse=reverse*10+mod;
number=number/10;
}
if(temp==reverse){
System.out.println("The next palindrome number is "+temp );
return true;
}
else
return false;

}  

}





program to reverse a String in Java.

 Write a program to reverse a String in Java.



package programs;

import java.io.FileNotFoundException;
import java.io.IOException;
public class StringReverse {
   public static void main(String args[]) throws FileNotFoundException, IOException {

       //original string
       String stmt = "This is Program to Reverse a String";
       System.out.println("Actual  String: " + stmt);

       //reversed string using Stringbuffer
       String reverseStr = new StringBuffer(stmt).reverse().toString();
       System.out.println("Reversed String using StringBuffer: " + reverseStr);

       //iterative method to reverse String 
       reverseStr = reverseiteration(stmt);
       System.out.println("Reversed  String using Iteration: " + reverseStr);

       //recursive method to reverse String
       reverseStr = reverseRecursion(stmt);
       System.out.println("Reversed  String  using Recursion: " + reverseStr);

   }

   public static String reverseiteration(String str) {
       StringBuilder strBuilder = new StringBuilder();
       char[] Chars = str.toCharArray();

       for (int x =Chars.length - 1; x >= 0; x--) {
           strBuilder.append(Chars[x]);
       }
       return strBuilder.toString();
   }

   public static String reverseRecursion(String str) {

       //base case to handle one char string and empty string
       if (str.length() < 2) {
           return str;
       }
       return reverseRecursion(str.substring(1)) + str.charAt(0);

   } }


java program for factorial of a given number.

Write a java program for factorial of a given number.
package programs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Factorial {
public static void main(String[] args) throws NumberFormatException, IOException  {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter  the Number");
int no=Integer.parseInt(br.readLine());
int fact=1;
for(int i=1;i<=no;i++){
fact=fact*i;
}
System.out.println("Factorial is: "+ fact);
}
}

Write a java program for swapping of two numbers

Write a java program for swapping of two numbers.

package programs;

import java.util.Scanner;

public class Swapping {
public static void main(String[] args)  {

int x, y;
     System.out.println("Enter x and y");
     Scanner in = new Scanner(System.in);
     x = in.nextInt();
     y = in.nextInt();  
     System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
     x = x+ y; 
     y = x -y; 
     x = x -y;
     
     System.out.println("After Swapping\nx = "+x+"\ny = "+y);
  }
}

java program to count number of unique words separated by comma (,) or newline and their occurrence from text file.


package programs;

import java.util.*;
import java.io.*;

public class uniquewrdsoccurence {

private String[] spliter;
private int[] count;
public void countWord(String Text) {

String temp1 = Text.replaceAll("[\\n]", " ");
String temp = temp1.replaceAll(",", " ");
spliter = temp.replaceAll("[.?!:;/]", "").split(" ");
count = new int[spliter.length];
for (int i = 0; i < spliter.length; i++) {
temp = spliter[i];
for (int k = 0; k < spliter.length; k++) {
if (temp.equalsIgnoreCase(spliter[k])) {
count[k]++;
}
}
}

printResult();
}

private void printResult() {

HashMap map = new HashMap();
int counter = 0;

for (int i = 0; i < spliter.length; i++) {
map.put(spliter[i].toLowerCase(), count[i]);
}

Iterator it = map.keySet().iterator();

System.out.println("Words             Count");
System.out.println("#######################");
while (it.hasNext()) {
counter++;

String temp = (String) it.next();

// prints the word 
System.out.print(temp);

// prints the spaces
for (int i = 0; i < (20 - temp.length()); i++) {
System.out.print(" ");
}

// print the value -total count
System.out.println(map.get(temp.toString()));

}
System.out.println("#######################");
System.out.println("Number of unique words in file:" + counter);
}

// main method 
public static void main(String[] arg) {
String pattern = "";
String str = null;

try {
FileInputStream filestream = new FileInputStream(
System.getProperty("user.dir") + "\\words.txt");
DataInputStream datastream = new DataInputStream(filestream);
BufferedReader Br = new BufferedReader(new InputStreamReader(datastream));
while ((str = Br.readLine()) != null) {
pattern = pattern.concat(str);
pattern = pattern.concat(" ");
}
datastream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
uniquewrdsoccurence wco = new uniquewrdsoccurence();
wco.countWord(pattern);
}

}

Read/write excel file in Java

 Read/write excel file in Java



package datatable;


import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
//import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.util.Calendar;


public class Xls_Reader {
public static String filename = System.getProperty("user.dir")+"\\src\\config\\testcases\\TestData.xlsx";
public  String path;
public  FileInputStream fis = null;
public  FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row   =null;
private XSSFCell cell = null;

public Xls_Reader(String path) {

this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();


}
// returns the row count in a sheet
public int getRowCount(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return 0;
else{
sheet = workbook.getSheetAt(index);
int number=sheet.getLastRowNum()+1;
return number;
}

}

// returns the data from a cell
public String getCellData(String sheetName,String colName,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);
int col_Num=-1;
if(index==-1)
return "";

sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num=i;
}
if(col_Num==-1)
return "";

sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(col_Num);

if(cell==null)
return "";
//System.out.println(cell.getCellType());
if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){
 
 String cellText  = String.valueOf(cell.getNumericCellValue());
 if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cal.get(Calendar.MONTH)+1 + "/" + 
                     cellText;
          
          //System.out.println(cellText);

        }

 
 
 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return ""; 
 else 
 return String.valueOf(cell.getBooleanCellValue());

}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}

// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);

if(index==-1)
return "";


sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";

 if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
 else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){
 
 String cellText  = String.valueOf(cell.getNumericCellValue());
 if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.MONTH)+1 + "/" +
                     cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cellText;
          
         // System.out.println(cellText);

        }

 
 
 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return "";
 else 
 return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist  in xls";
}
}

// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path); 
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);


row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;

sheet.autoSizeColumn(colNum); 
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   // cell style
   //CellStyle cs = workbook.createCellStyle();
   //cs.setWrapText(true);
   //cell.setCellStyle(cs);
   cell.setCellValue(data);

   fileOut = new FileOutputStream(path);

workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}


// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
//System.out.println("setCellData setCellData******************");
try{
fis = new FileInputStream(path); 
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);
//System.out.println("A");
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}

if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum); //ashish
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   cell.setCellValue(data);
   XSSFCreationHelper createHelper = workbook.getCreationHelper();

   //cell style for hyperlinks
   //by default hypelrinks are blue and underlined
   CellStyle hlink_style = workbook.createCellStyle();
   XSSFFont hlink_font = workbook.createFont();
   hlink_font.setUnderline(XSSFFont.U_SINGLE);
   hlink_font.setColor(IndexedColors.BLUE.getIndex());
   hlink_style.setFont(hlink_font);
   //hlink_style.setWrapText(true);

   XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
   link.setAddress(url);
   cell.setHyperlink(link);
   cell.setCellStyle(hlink_style);
     
   fileOut = new FileOutputStream(path);
workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}



// returns true if sheet is created successfully else false
public boolean addSheet(String  sheetname){

FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
    fileOut.close();    
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();    
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
//System.out.println("**************addColumn*********************");

try{
fis = new FileInputStream(path); 
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

sheet=workbook.getSheetAt(index);

row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);

//cell = row.getCell();
//if (cell == null)
//System.out.println(row.getLastCellNum());
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
       
       cell.setCellValue(colName);
       cell.setCellStyle(style);
       
       fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();    

}catch(Exception e){
e.printStackTrace();
return false;
}

return true;


}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path); 
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);

   

for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;

}
  // find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}

// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;

sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

if(row==null)
return -1;

return row.getLastCellNum();



}
//String sheetName, String testCaseName,String keyword ,String URL,String message
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
//System.out.println("ADDING addHyperLink******************");

url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;

   sheet = workbook.getSheet(sheetName);
   
   for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
    //System.out.println("**caught "+(i+index));
    setCellData(sheetName, screenShotColName, i+index, message,url);
    break;
    }
   }


return true; 
}
public int getCellRowNum(String sheetName,String colName,String cellValue){

for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
    return i;
    }
   }
return -1;

}


Back to Selenium Interview Questions and Answers

Java program to print Fibonacci series.

Java program to print Fibonacci series.

package programs;

public class Fibonacci {
public static void main(String[] args)  {
int Count = 10;
    int[] feb = new int[Count];
    feb[0] = 0;
    feb[1] = 1;
    for(int i=2; i < Count; i++){
        feb[i] = feb[i-1] + feb[i-2];
    }

    for(int i=0; i< Count; i++){
            System.out.print(feb[i] + " ");
    }
}
}