Wednesday, 8 January 2014

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");
        }
    }

}


   


Java: Piglatin

package piglatin2;
import java.util.Scanner;
/**
 *
 * @author ravikiran
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String statement, result, another;
      piglatin translator = new piglatin();

      do
      {
         System.out.println ();
         System.out.println ("Enter a sentence (no punctuation):");
         Scanner input= new Scanner(System.in);
         statement = input.nextLine();

         System.out.println ();
         result = translator.translate (statement);
         System.out.println ("That sentence in Pig Latin is:");
         System.out.println (result);

         System.out.println ();
         System.out.print ("Translate another sentence (y/n)? ");
         another = input.nextLine();
      }
      while (another.equalsIgnoreCase("y"));
    }

}

package piglatin2;
import java.util.StringTokenizer;
/**
 *
 * @author ravikiran
 */
public class piglatin extends Main{
    public String translate(String statement)
{
String string=null;

StringTokenizer input=new StringTokenizer(statement);
while(input.hasMoreTokens())
{
string=string+translator(input.nextToken());
string=string+" ";
}
return string;


}
public String translator(String word )
{
String string=null;
if(!vowel(word))
{

string=word+"ay";

}
else
{
string=word.substring(1) + word.substring(0,1) + "ay";
}
return string;
}

private static boolean vowel (String word)
{
String Vowels = "aeiou";

char letter = word.charAt(0);

return (Vowels.indexOf(letter) != -1);
}

}

Friday, 3 January 2014

C# Using Enum: GTK style

using System;
using System.Collections;
using Gtk;

namespace EmpIEnum
{
class MainClass
{
public static void Main (string[] args)
{
EmployeeCollection E=new EmployeeCollection();
foreach(Employee e in E)
Console.WriteLine(e.Name+"\t\t"+e.Id+"\t\t"+e.Salary);
Console.WriteLine();
}
}
}



using System;
using System.Collections;

namespace EmpIEnum
{
public class Employee
{
public string name;
public int id;
public long salary;

public Employee (string Name,int Id,long salary)
{
name=Name;
id=Id;
salary=Salary;
}
public string Name{
get {return name;}
set {name=value;}
}

public int Id{
get{return id;}
set {id=value;}
}
public long Salary{
get{return salary;}
set {salary=value;}
}

}

}


using System;
using System.Collections;
namespace EmpIEnum
{
public class EmployeeCollection:IEnumerable,IEnumerator
{
Employee[] empcollection;
int pos=-1;

public EmployeeCollection ()
{
empcollection=new Employee[5]
{
new Employee("Ravi",123,2000),
new Employee("Kiran",234,3000),
new Employee("Ranju",345,4000),
new Employee("Ram",456,5000),
new Employee("Maansi",567,6000),
};
}
public IEnumerator GetEnumerator()
{
return(IEnumerator)this;
}
public bool MoveNext(){
pos++;
return(pos<empcollection.Length);
}
public void Reset(){
pos=0;
}
public object Current{
get{return empcollection[pos];}
}

}
}