Friday, 10 January 2014

Java : Change case of the entered string from uppercase to lowercase

public class Ques2 {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    //ascii A=65 Z=90 a=97
    System.out.println("Enter UPPERCASE");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   // String input = br.readLine().toLowerCase();
    char c;
    char[] word=br.readLine().toCharArray();
   for(int i :word)
   {
       if(i>=65 && i<=90){
       i=i+32 ;
       c=(char) i;
        System.out.println(c);
       }
       else{
           c=(char)i;
           System.out.println(c);
       }
   }

}
}

Java: String Compression - How to compress string in the given format

Write a routine that takes as input a string such as "aabbccdef" and outputs "a2b2c2def" or "a4bd2g4" for "aaaabddgggg". Write a ship quality code.


import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine().toLowerCase();
       StringBuilder result = new StringBuilder();
        char currentCharacter;
        int count;

        for(int i = 0; i < input.length(); i++) {
            currentCharacter = input.charAt(i);
            count = 1;
            while(i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
                count++;
                i++;
            }
            result.append(currentCharacter);
            result.append(count);
        }

        System.out.println(""+result);
    }
}

Thursday, 9 January 2014

Java : Program to print all permutations of a given string.

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Below are the permutations of string ABC. ABC, ACB, BAC, BCA, CAB, CBA

public class Ques2 {

    /**
     * @param args the command line arguments
     */
   public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

        
    public static void main(String[] args) throws IOException {

       String str="abc";
       permutation(str);
}
}

Java:Find position of a string in another string.

Find position of a string in another string. For example your first string is 'careerstack' and the second string is 'stack' then the output should be 7.


public class Ques2 {

    /**
     * @param args the command line arguments
     */
   
        
    public static void main(String[] args) throws IOException {

       String match = "kiran";
        String text = "kiranhellooooookiran";
        int i =0;
        while((i=(text.indexOf(match,i)+1))>0)
            System.out.println(i-1);         
        }  

}

Java:Find the number of times each character occurs in the string.

Calculate the frequency of each character in a given string
eg teddy d= 2 e=1 t=1 y=1

import java.io.IOException;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        String str = "hello kiran";
        int count = 0;
        String temp = "";
        for (int i = 0; i < str.length(); i++) {

            char c = str.charAt(i);  // take one character (c) in string

            for (int j = i; j < str.length(); j++) {

                char k = str.charAt(j);
                // take one character (c) and compare with each character (k) in the string
                // also check that character (c) is not already counted.
                // if condition passes then increment the count.
                if (c == k && temp.indexOf(c) == -1) {
                    count = count + 1;
                }
            }

            if (temp.indexOf(c) == -1) // if it is not already counted
            {
                temp = temp + c; // append the character to the temp indicating
                // that you have already counted it.

                System.out.println("Character   " + c + "   occurs   " + count + "    times");
            }
            // reset the counter for next iteration 
            count = 0;

        }


    }
}

Java: find if two words are anagram in an array of strings




/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

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

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        String AS[] = new String[]{"", "", "", "", "", ""};
        System.out.println("Enter array of strings");
        for (int i = 0; i < AS.length; i++) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            AS[i] = br.readLine().toLowerCase();
        }
        for (int i = 0; i < AS.length; i++) {
            for (int j = i + 1; j < AS.length; j++) {
                if (AS[i].length() == AS[j].length()) {
                    char c1[] = null;
                    char c2[] = null;
                    c1 = AS[i].toCharArray();
                    c2 = AS[j].toCharArray();

                    Arrays.sort(c1);
                    Arrays.sort(c2);

                    if (Arrays.equals(c1, c2)) {
                        System.out.println("Both strings are equal and hence they have anagram at " +i+j);
                    } else {
                        System.out.println("Sorry No anagram in the strings entered");
                    }
                }
            }
        }



    }
}

Wednesday, 8 January 2014

Java: finding if two words are anagrams of each other

The steps are:
  1. check the length of of both the words/strings if they are equal then only proceed to check for anagram else do nothing
  2. sort both the words/strings and then compare
package anagram;

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

/**
 *
 * @author Sunshine
 */
public class Anagram {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        System.out.println("Enter the first string");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s1 = br.readLine().toLowerCase();
        System.out.println("Enter the Second string");
        BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
        String s2 = br2.readLine().toLowerCase();
        char c1[] = null;
        char c2[] = null;
        if (s1.length() == s2.length()) {


            c1 = s1.toCharArray();
            c2 = s2.toCharArray();

            Arrays.sort(c1);
            Arrays.sort(c2);

            if (Arrays.equals(c1, c2)) {
                System.out.println("Both strings are equal and hence they have anagram");
            } else {
                System.out.println("Sorry No anagram in the strings entred");
            }

        } else {
            System.out.println("Sorry the string do not have anagram");

Java: Remove duplicate elements in a string

Given a string *Str of ASCII characters, write the pseudo code to remove the duplicate elements present in them. For example, if the given string is "Potato", then, the output has to be "Pota". Additional constraint is, the algorithm has to be in-place( no extra data structures allowed).



public class HelloWorld{

     public static void main(String []args){
         String str="potato";
        int[] A = new int[256];//maximum value of an ASCII character
        StringBuffer sb = new StringBuffer();

        int len = str.length();
        for (int i = 0; i < len; i++)
        {
            char c = str.charAt(i);
            if (A[c] == 0)
            {
                A[c] = 1;
                sb.append(c);
            }
        }

    sb.toString();
            
    System.out.println(""+sb);
     }
}

Java: Replace given pattern with 'X'

Replace all occurrence of the given pattern to 'X'.For example, given that the pattern = 'abc', replace 'abcdeffdfegabcabc' with 'XdeffdfegX'. Note that multiple occurrences of abc's that are contiguous will be replaced with only one 'X'.

public class HelloWorld{

     public static void main(String []args){
         String s1="Helloabckiranabchowareabcyou";
    s1=s1.trim().replaceAll("abc", "X");
    System.out.println(""+s1);
     }

}

Java: Write a program to compact spaces in a string

Write a program to compact spaces in a string i.e. Given a string you have to remove multiple occurrences of blank spaces by a single space and do that in a single pass of the arrays

public class HelloWorld{

     public static void main(String []args){
         String s1="Hello    kiran   how are   you";
    s1=s1.trim().replaceAll("\\s+", " ");
    System.out.println(""+s1);
     }

}

Java: Merge two unsorted arrays and remove duplicates

Merge two unsorted array and remove the duplicate from the resultant array. example
Array1 = {"are","you","there"}
Array2={"how","are","you"}
output={"how","are","you","there"}


public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
          String[] Array1 = {"how","are","you"};
    String[] Array2 = {"are","you","there","now"};
    
    HashMap ht=new HashMap();
    for(int i=0;i<Array1.length;i++)
    {
        if(!ht.containsValue(Array1[i])) {
           ht.put(Array1[i], Array1[i]);
        }
    }
     for(int i=0;i<Array2.length;i++)
    {
        if(!ht.containsValue(Array2[i])) {
           ht.put(Array2[i], Array2[i]);
        }
    }
   //  for(int i=0;i<ht.size();i++){
         System.out.println(ht.values());
   //  }
    }
}

Java : Check if a string is an interleaved sequence of other 2 strings

public class HelloWorld{

     public static void main(String []args){
       String s1 = "ravi", s2 = "123456789";
StringBuilder sb = new StringBuilder();

int minLength = Math.min(s1.length(), s2.length());
for (int i = 0; i < minLength; i++){
    sb.append(s1.charAt(i));
    sb.append(s2.charAt(i));
}

for (int i = minLength; i < s1.length(); i++){
    sb.append(s1.charAt(i));
}

for (int i = minLength; i < s2.length(); i++){
    sb.append(s2.charAt(i));
}
String s3="vreornaaldo";
if(s3.equals(sb)){
    System.out.println("OKAY");
}
System.out.println(sb.toString());


       }
}

Java : Remove comments from a text file

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * @author Sunshine
 */
public class RemoveComments {
    void RemoveComments(String inputFilePath, String outputFilePath) throws FileNotFoundException, IOException {
    File in = new File(inputFilePath);
    File out = new File(outputFilePath);
    BufferedReader bufferedreader = new BufferedReader(new FileReader(in));
    PrintWriter pw = new PrintWriter(new FileWriter(out));
    String line = null, lineToRemove = null;
    while ((line = bufferedreader.readLine()) != null) {
        if (line.startsWith("/*") && line.endsWith("*/")) {
            lineToRemove = line;
        }
        if (!line.trim().equals(lineToRemove)) {
            pw.println(line);
            pw.flush();
        }
    }
}
}

Java : Make a HashMap for the class Student. class Student { String name; Date dateOfBirth; Integer fees; }



Ques2.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

/**
 *
 * @author Sunshine
 */
public class Ques2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Student_HM_Demo s=new Student_HM_Demo();
        s.add(new Student("ravi",10,125));
        s.add(new Student("Kiran",907,12));
        //s.print();
    }
}


 Student .java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

/**
 *
 * @author Sunshine
 */
class Student {
     private String Name;
    private double DOB;
    private int Fee;

    public Student(String name, double dob, int fee) {
        this.Name = name;
        this.DOB = dob;
        this.Fee = fee;
    }
    // Getter-setter

    Student() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public String get_student_name() {
        return this.Name;
    }

    public double get_student_D0B() {
        return this.DOB;
    }

    public int get_student_fee() {
        return this.Fee;
    }

    public void set_student_name(String name) {
        this.Name = name;
    }

    public void set_student_D0B(double DOB) {
        this.DOB = DOB;
    }

    public void set_student_fee(int fee) {
        this.Fee = fee;
    }

    public String toString() {
        return "Student[+Name+DOB+Fee]";
    }
}

Student_HM_Demo.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

import java.util.HashMap;

/**
 *
 * @author Sunshine
 */
public class Student_HM_Demo {
     HashMap<String, Student> map;

    public Student_HM_Demo() {
        map = new HashMap<String, Student>();
    }

    public void add(Student obj) {
        map.put(obj.get_student_name(), obj);
    }

    public void print() {
        for (Student s : map.values()) {
            System.out.println(""+s.get_student_name());
            System.out.println(""+s.get_student_D0B());
            System.out.println(""+s.get_student_fee());
        }
    }
}

Monday, 6 January 2014

Java: WAP to print the sum of characters in a String. Assuming that A=1, B=2, C=3.....So DAD will be 4+1+4=9.

import java.io.*;
import java.io.InputStreamReader;
//import sun.security.util.Length;


public class HelloWorld{

     public static void main(String []args){
       // System.out.println("Hello World");
       int sum=0;
       String br="DAD";
 
      char[] word=br.toLowerCase().toCharArray();
       for(int i :word)
       {
           sum=sum +i -96;
       }
       System.out.println("Sum of characters:"+sum);
     }
}




Java : Project to build a Computer based Test

Hi Guys,


I created a dummy computer based test application. The code/UI can be downloaded from here: Computer based Test


As always comments , questions and suggestions are welcome ;)

Android : Step by Step Guide to build a Quiz application

This is for all those who have been flooding my mailbox for the steps to create a basic android application.

Please find the step by step guide to build a basic quiz application in android @ : Guide


Hope you have good time reading it:)

Suggestions and Questions are welcome ;)

Java: Simple Bank Account with Exception Handling

Account.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bank;

/**
 *
 * @author ravikiran
 */
public class Account {
    private long AccNumber,balance;
    private String AccHolder;

    public Account(long num,long bal,String name){
        AccNumber=num;
        balance=bal;
        AccHolder=name;
    }
    public void withdraw(long amount)throws InsufficientFundsException
    {
       
             if(amount>balance)
                 throw new InsufficientFundsException(amount);
             else
             {
                 balance=balance-amount;
            System.out.print("The current balance is"+balance);

            }
    }
      public void deposit(long amount)throws InvalidTransactionException
              {

             if(amount<=0)
                 throw new InvalidTransactionException(amount);
             else
             {
                 balance=balance+amount;
            System.out.print("The current balance is"+balance);

            }

    }
}


InsufficientFundsException.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bank;

import java.util.Scanner;

/**
 *
 * @author ravikiran
 */
class InsufficientFundsException extends Exception {
    long amt;
    public InsufficientFundsException(long amount)
    {
       
        
        amt=amount;
    }
   public  String tostring(){
        return"InsufficientFundsException";
    }



}

InvalidTransactionException.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bank;

/**
 *
 * @author ravikiran
 */
class InvalidTransactionException extends Exception {
    long amt;
    public  InvalidTransactionException(long amount)
    {


        amt=amount;
    }
   public  String tostring(){
        return" Invalid Transaction Exception";
    }


}


Main.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bank;

import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author ravikiran
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("select your operation");
        System.out.println("1.withdraw");
        System.out.println("2.Deposit");

        Account a=new Account(215,20000,"ravi");
        Scanner input=new Scanner(System.in);
        int b=input.nextInt();

        switch(b)
        {

        case 1:
        try{

            a.withdraw(20000);
        }
        catch(InsufficientFundsException e){
            JOptionPane.showMessageDialog(null,"Dear Customer You Have insufficient amount in your Account.","Error",JOptionPane.ERROR_MESSAGE);
            
        }
        break;
        case 2:try {

            a.deposit(10);
        }
        catch(InvalidTransactionException e){
            JOptionPane.showMessageDialog(null,"Dear Customer You Entered Invalid Amount","Error",JOptionPane.ERROR_MESSAGE);
            
        }
        break;
        default: System.out.print("Invalid operation");
        }
    }

}