Wednesday, 23 October 2013

Java program to find sum of numbers present in a string..

Numbers are apart from from characters by spaces ...like "12 gaurav 3"

Here is the code ....


       
import java.io.*;
public class BetterProgrammerTask {

 public static int getSumOfNumbers(String s) {
  int sum = 0;
  String[] bw = s.split(" ");
  for (int k = 0; k < bw.length; k++) {
   if (isNumeric(bw[k]) == true)
    sum = sum + Integer.parseInt(bw[k]);
  }
  return sum;
 }

 public static boolean isNumeric(String kts) {
  try {
   double d = Double.parseDouble(kts);
  } catch (NumberFormatException nfe) {
   return false;
  }
  return true;
 }

 public static void main(String args[]) throws Exception {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String str = br.readLine();
  getSumOfNumbers(str);
  System.out.println(getSumOfNumbers(str));
 }
}

       
 

Sunday, 20 October 2013

Java program to find the greater of two numbers without using any relational operator ...

Here is the code .....



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

public class Greater {

 int great(int a, int b) {
  int c = a - b;
  int k = (c >> 31) & 0x1;
  System.out.println(k);
  //int g=a-k(a-b);
  return a - k * (a - b);
 }
 public static void main(String args[]) {
  int a = 6, b = 3;
  Greater d = new Greater();
  System.out.println("the greater no. is " + d.great(a, b));
 }
}

       
 

Java program to find sum of two numbers without using '+' operator ..

Here is the code ....



       
public class Sumfrom {

 int Sumis(int a, int b) {
  if (b == 0) return a;
  int sum = (a ^ b);
  int carry = (a & b) << 1;
  return Sumis(sum, carry);
 }

 public static void main(String args[]) {
  int a = 34, b = 2;
  Sumfrom d = new Sumfrom();
  System.out.println("the sum is " + d.Sumis(a, b));
 }

}

       
 

Tuesday, 15 October 2013

Java program to remove duplicates from a character array .

Here is the code ....



       

public class P13 {
 public static void main(String args[]) {
  char[] chr = {
   'g',
   'a',
   'g',
   'r',
   'p',
   'k',
   't',
   'k',
   'r',
   's'
  };
  boolean[] boo = new boolean[256];
  int cal = 0;
  for (int i = 0, val; i < chr.length; i++) {

   if (i < chr.length - cal) {

    val = chr[i];
    if (boo[val]) {
     cal = cal + 1;

     for (int k = i; k < chr.length - 1; k++) {
      chr[k] = chr[k + 1];
     }
     chr[chr.length - 1] = '\0';
     i = i - 1;
    } else boo[val] = true;
    //System.out.println("hello2");

   } else {
    break;
   }
  }

  for (int h = 0; h < chr.length; h++)
   System.out.print(chr[h]);

 }
}

       
 

java program to copy values from a arraylist to array.

Here is the source code ...


       

import java.util.*;
class Arraylist_to_array {
 public static void main(String[] a) {
  ArrayList k = new ArrayList();
  k.add(new Integer(1));
  k.add(new Integer(2));
  k.add(new Integer(3));
  k.add(new Integer(4));
  k.add(new Integer(5));
  k.add(new Integer(4));
  System.out.println("contents of ArrayList=" + k);

  Object arr[] = new Object[6];
  arr = k.toArray();
  int sum = 0, i;
  for (i = 0; i < arr.length; i++) {
   sum += ((Integer) arr[i]).intValue();
  }
  System.out.println("sum of the contents of the array=" + sum);
 }
}

       
 

A program to check whether a string is a substring of a given another string or not .

Here is the source code .....


       

import java.io.*;
public class P18 {
 public static void main(String args[]) {
  String s1 = "ur";
  String s2 = "gaurav";
  P18 ab = new P18();
  ab.isString(s1, s2);
 }

 void isString(String s1, String s2) {
  int k;

  if (s1.length() > s2.length()) {
   System.out.println("string is not substring");
   return;
  }

  for (int i = 0, s = 0; i < s2.length() - s1.length(); i++) {
   if (s2.charAt(i) == s1.charAt(s)) {
    for (k = i; k < i + s1.length(); k++) {
     if (s1.charAt(s) == s2.charAt(k)) {
      s++;
     } else {
      s = 0;
      break;
     }
    }
    if (k == i + s1.length()) {
     System.out.println("string is substring");
     return;
    }
   }

  }
  System.out.println("string is not the substring");
 }
}

       
 

Sunday, 13 October 2013

Source code for Calculator application implemented using java swing API

Source code for Calculator application implemented using java swing API ......

here is the code for the application ....its a mini project although a desktop application and it works well because i thoroughly tested it ...



       

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;

public class Calculator extends JFrame implements ActionListener {
 final int MAX_INPUT_LENGTH = 15;
 final int INPUT_MODE = 0;
 final int RESULT_MODE = 1;
 final int ERROR_MODE = 2;
 int displayMode;

 boolean clearOnNextDigit, percent;
 double lastNumber;
 String lastOperator;

 private JMenu jmenuFile, jmenuHelp;
 private JMenuItem jmenuitemExit, jmenuitemAbout;

 private JLabel jlbOutput;
 private JButton jbnButtons[];
 private JPanel jplMaster, jplBackSpace, jplControl;

 Font f1 = new Font("Times New Roman", 0, 18);
 Font f12 = new Font("Times New Roman", 1, 18);

 public Calculator() {
  jmenuFile = new JMenu("File");
  jmenuFile.setFont(f12);
  jmenuFile.setMnemonic(KeyEvent.VK_F);

  jmenuitemExit = new JMenuItem("Exit");
  jmenuitemExit.setFont(f1);
  jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
   ActionEvent.CTRL_MASK));
  jmenuFile.add(jmenuitemExit);

  jmenuHelp = new JMenu("Help");
  jmenuHelp.setFont(f12);
  jmenuHelp.setMnemonic(KeyEvent.VK_H);

  jmenuitemAbout = new JMenuItem("About Calculator");
  jmenuitemAbout.setFont(f1);
  jmenuHelp.add(jmenuitemAbout);

  JMenuBar mb = new JMenuBar();
  mb.add(jmenuFile);
  mb.add(jmenuHelp);
  setJMenuBar(mb);

  setBackground(Color.gray);

  jplMaster = new JPanel();

  jlbOutput = new JLabel("0");
  jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);
  jlbOutput.setBackground(Color.WHITE);
  jlbOutput.setOpaque(true);
  getContentPane().add(jlbOutput, BorderLayout.NORTH);

  jbnButtons = new JButton[18];
  JPanel jplButtons = new JPanel();
  for (int i = 0; i <= 9; i++) {
   jbnButtons[i] = new JButton(String.valueOf(i));
  }

  jbnButtons[10] = new JButton(".");
  jbnButtons[11] = new JButton("=");
  jbnButtons[12] = new JButton("/");
  jbnButtons[13] = new JButton("*");
  jbnButtons[14] = new JButton("-");
  jbnButtons[15] = new JButton("+");

  jplBackSpace = new JPanel();
  jplBackSpace.setLayout(new GridLayout(1, 1, 2, 3));

  jbnButtons[16] = new JButton("Backspace");
  jplBackSpace.add(jbnButtons[16]);
  jplControl = new JPanel();
  jplControl.setLayout(new GridLayout(1, 2, 2, 3));

  jbnButtons[17] = new JButton("C");
  jplControl.add(jbnButtons[17]);

  for (int i = 0; i < jbnButtons.length; i++) {
   jbnButtons[i].setFont(f12);

   if (i < 10)
    jbnButtons[i].setForeground(Color.blue);

   else
    jbnButtons[i].setForeground(Color.red);
  }

  jplButtons.setLayout(new GridLayout(4, 5, 2, 4));

  for (int i = 7; i <= 9; i++) {
   jplButtons.add(jbnButtons[i]);
  }

  jplButtons.add(jbnButtons[10]);
  jplButtons.add(jbnButtons[12]);


  for (int i = 4; i <= 6; i++) {
   jplButtons.add(jbnButtons[i]);
  }

  jplButtons.add(jbnButtons[14]);
  jplButtons.add(jbnButtons[11]);



  for (int i = 1; i <= 3; i++) {
   jplButtons.add(jbnButtons[i]);
  }

  jplButtons.add(jbnButtons[0]);
  jplButtons.add(jbnButtons[13]);
  jplButtons.add(jbnButtons[15]);
  jplButtons.add(jbnButtons[16]);
  jplButtons.add(jbnButtons[17]);


  jplMaster.setLayout(new BorderLayout());
  jplMaster.add(jplBackSpace, BorderLayout.WEST);
  jplMaster.add(jplControl, BorderLayout.EAST);
  jplMaster.add(jplButtons, BorderLayout.SOUTH);

  getContentPane().add(jplMaster, BorderLayout.SOUTH);
  requestFocus();

  for (int i = 0; i < jbnButtons.length; i++) {
   jbnButtons[i].addActionListener(this);
  }

  jmenuitemAbout.addActionListener(this);
  jmenuitemExit.addActionListener(this);

  clearAll();

  addWindowListener(new WindowAdapter() {

   public void windowClosed(WindowEvent e) {
    System.exit(0);
   }
  });
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }


 public void actionPerformed(ActionEvent e) {
  double result = 0;

  if (e.getSource() == jmenuitemAbout) {
   JDialog dlgAbout = new CustomABOUTDialog(this, "About Java Swing Calculator", true);
   dlgAbout.setVisible(true);
  } else if (e.getSource() == jmenuitemExit) {
   System.exit(0);
  }
  for (int i = 0; i < jbnButtons.length; i++) {
   if (e.getSource() == jbnButtons[i]) {
    switch (i) {
     case 0:
      addDigitToDisplay(i);
      break;

     case 1:
      addDigitToDisplay(i);
      break;

     case 2:
      addDigitToDisplay(i);
      break;

     case 3:
      addDigitToDisplay(i);
      break;

     case 4:
      addDigitToDisplay(i);
      break;

     case 5:
      addDigitToDisplay(i);
      break;

     case 6:
      addDigitToDisplay(i);
      break;

     case 7:
      addDigitToDisplay(i);
      break;

     case 8:
      addDigitToDisplay(i);
      break;

     case 9:
      addDigitToDisplay(i);
      break;


     case 10: // decimal point
      addDecimalPoint();
      break;

     case 11: // =
      processEquals();
      break;

     case 12: // divide
      processOperator("/");
      break;

     case 13: // *
      processOperator("*");
      break;

     case 14: // -
      processOperator("-");
      break;

     case 15: // +
      processOperator("+");
      break;



     case 16: // backspace
      if (displayMode != ERROR_MODE) {
       setDisplayString(getDisplayString().substring(0,
        getDisplayString().length() - 1));

       if (getDisplayString().length() < 1)
        setDisplayString("0");
      }
      break;


     case 17: // C
      clearAll();
      break;
    }
   }
  }
 }

 void setDisplayString(String s) {
  jlbOutput.setText(s);
 }

 String getDisplayString() {
  return jlbOutput.getText();
 }

 void addDigitToDisplay(int digit) {
  if (clearOnNextDigit)
   setDisplayString("");

  String inputString = getDisplayString();

  if (inputString.indexOf("0") == 0) {
   inputString = inputString.substring(1);
  }

  if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH) {
   setDisplayString(inputString + digit);
  }


  displayMode = INPUT_MODE;
  clearOnNextDigit = false;
 }

 void addDecimalPoint() {
  displayMode = INPUT_MODE;

  if (clearOnNextDigit)
   setDisplayString("");

  String inputString = getDisplayString();
  if (inputString.indexOf(".") < 0)
   setDisplayString(new String(inputString + "."));
 }



 void clearAll() {
  setDisplayString("0");
  lastOperator = "0";
  lastNumber = 0;
  displayMode = INPUT_MODE;
  clearOnNextDigit = true;
 }



 double getNumberInDisplay() {
  String input = jlbOutput.getText();
  return Double.parseDouble(input);
 }

 void processOperator(String op) {
  if (displayMode != ERROR_MODE) {
   double numberInDisplay = getNumberInDisplay();

   if (!lastOperator.equals("0")) {
    try {
     double result = processLastOperator();
     displayResult(result);
     lastNumber = result;
    } catch (DivideByZeroException e) {}
   } else {
    lastNumber = numberInDisplay;
   }

   clearOnNextDigit = true;
   lastOperator = op;
  }
 }

 void processEquals() {
  double result = 0;

  if (displayMode != ERROR_MODE) {
   try {
    result = processLastOperator();
    displayResult(result);
   } catch (DivideByZeroException e) {
    displayError("Cannot divide by zero!");
   }

   lastOperator = "0";
  }
 }

 double processLastOperator() throws DivideByZeroException {
  double result = 0;
  double numberInDisplay = getNumberInDisplay();

  if (lastOperator.equals("/")) {
   if (numberInDisplay == 0)
    throw (new DivideByZeroException());

   result = lastNumber / numberInDisplay;
  }

  if (lastOperator.equals("*"))
   result = lastNumber * numberInDisplay;

  if (lastOperator.equals("-"))
   result = lastNumber - numberInDisplay;

  if (lastOperator.equals("+"))
   result = lastNumber + numberInDisplay;

  return result;
 }

 void displayResult(double result) {
  setDisplayString(Double.toString(result));
  lastNumber = result;
  displayMode = RESULT_MODE;
  clearOnNextDigit = true;
 }

 void displayError(String errorMessage) {
  setDisplayString(errorMessage);
  lastNumber = 0;
  displayMode = ERROR_MODE;
  clearOnNextDigit = true;
 }

 public static void main(String args[]) {
  Calculator calci = new Calculator();
  Container contentPane = calci.getContentPane();
  calci.setTitle("Java Swing Calculator");
  calci.setSize(400, 360);
  calci.pack();
  calci.setLocation(300, 290);
  calci.setVisible(true);
  calci.setResizable(false);
 }

}
class DivideByZeroException extends Exception {
 public DivideByZeroException() {
  super();
 }

 public DivideByZeroException(String s) {
  super(s);
 }
}

class CustomABOUTDialog extends JDialog implements ActionListener {
 JButton jbnOk;

 CustomABOUTDialog(JFrame parent, String title, boolean modal) {
  super(parent, title, modal);
  setBackground(Color.black);

  JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));

  StringBuffer text = new StringBuffer();
  text.append("Calculator Information\n\n");
  text.append("Developer: Amita Sikarwar\n class:  B.C.A 5th sem\n Roll No:  124\n\n");
  text.append("Version: 1.0");

  JTextArea jtAreaAbout = new JTextArea(5, 16);
  jtAreaAbout.setText(text.toString());
  jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));
  jtAreaAbout.setEditable(false);

  p1.add(jtAreaAbout);
  p1.setBackground(Color.red);
  getContentPane().add(p1, BorderLayout.CENTER);

  JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
  jbnOk = new JButton(" OK ");
  jbnOk.addActionListener(this);

  p2.add(jbnOk);
  getContentPane().add(p2, BorderLayout.SOUTH);

  setLocation(600, 350);
  setResizable(false);

  addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
    Window aboutDialog = e.getWindow();
    aboutDialog.dispose();
   }
  });

  pack();
 }

 public void actionPerformed(ActionEvent e) {
  if (e.getSource() == jbnOk) {
   this.dispose();
  }
 }

}

       
 

Friday, 11 October 2013

Reversing a string using stack in java....

Reversing a string using stack in java....


       

here is the code..
import java.util.*;
import java.io.*;
public class Reverse {
 public static void main(String args[]) throws Exception {
  String name = "gaurav";
  int k = name.length();
  Stack ab = new Stack();

  char[] name1 = new char[k];

  for (int i = 0; i < k; i++)
   ab.push(new Character(name.charAt(i)));

  for (int j = 0; j < k; j++)
   name1[j] = ((Character) ab.pop()).charValue();

  for (char s: name1)
   System.out.print(s);

 }
}

       
 

Saturday, 5 October 2013

Quicksort implemented using Java......

/*Java program for sorting an array using quicksort ...*/

here is the code ...


       

import java.io.*;
public class Quick {

 public static void Quicksort(int[] arr, int lower, int upper) {
  int i = 0;
  if (lower < upper) {
   i = split(arr, lower, upper);
   Quicksort(arr, lower, i - 1);
   Quicksort(arr, i + 1, upper);
  }
 }

 public static int split(int[] arr, int lower, int upper) {
  int t = 0;
  int p = lower + 1;
  int q = upper;
  try {
   while (p <= q) {

    while (arr[p] < arr[lower])
     p++;

    while (arr[q] > arr[lower])
     q--;
    if (q > p) {
     t = arr[q];
     arr[q] = arr[p];
     arr[p] = t;
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  t = arr[q];
  arr[q] = arr[lower];
  arr[lower] = t;
  return q;

 }


 public static void main(String args[]) {
  int[] arr = {
   6,
   7,
   9,
   3,
   5,
   10,
   34,
   13
  };
  int lower = 0, upper = arr.length - 1;
  Quicksort(arr, lower, upper);

  for (int k: arr)
   System.out.println(k);

 }
}

       
 

Saturday, 7 September 2013

java program to check whether a string is made up of unique characters or not ..

/*java program to check whether a string is made up of unique characters or not ..*/


       

import java.io.*;
public class P11 {
 public static void main(String args[]) {
  boolean[] ch = new boolean[256];

  String name = "gaurv##";

  for (int i = 0, val; i < name.length(); i++) {
   val = name.charAt(i);
   if (ch[val]) {
    System.out.println("string is not unique");
    return;
   } else {
    ch[val] = true;
   }
  }
  System.out.println("string is unique");
 }
}

       
 

Check whether two strings are anagrams or not using java....

/*java program to check whether two strings are anagrams */


       

import java.io.*;
public class P14 {
 public static void main(String args[]) {
  char chr[] = {
   'g',
   'a',
   'u',
   'r',
   'a',
   'v',
   's'
  };
  char chr1[] = {
   'v',
   'a',
   'g',
   'a',
   'u',
   'r',
   'k'
  };
  int[] boo = new int[256];
  if (chr.length != chr1.length) {
   System.out.println("strings are not anagrams");
   return;
  }

  for (int i = 0, val; i < chr.length; i++) {
   val = chr[i];
   boo[val] = boo[val] + 1;
  }


  try {
   for (int k = 0, val1; k < chr1.length; k++) {
    val1 = chr1[k];
    if (boo[val1] != 0) {
     boo[val1] = boo[val1] - 1;
    } else {
     System.out.println("strings are not anagrams");
     return;
    }
   }
  } catch (Exception e) {
   System.out.println("error found");
  }
  System.out.println("strings are anagrams ");
 }
}

       
 

java program to replace the spaces in a string by '%20'.

Here is the code ....


       

public class P15 {
 public static void main(String args[]) {
  String name = "gaurav kumar yadav";
  int val = 0;
  for (int i = 0; i < name.length(); i++)
   if (name.charAt(i) == ' ') val = val + 1;

  char[] chr = new char[name.length() + 2 * val];
  for (int l = 0, s = 0; l < name.length(); l++) {
   if (name.charAt(l) != ' ') {
    chr[s] = name.charAt(l);
    s++;
   } else {
    chr[s] = '%';
    chr[++s] = '2';
    chr[++s] = '0';
    s++;
   }

  }
  String name1 = new String(chr);
  System.out.println(name1);
 }
}

       
 

Wednesday, 28 August 2013

Java program to implement comparable interface ......

Here is the code ;-....



       

import java.util.*;
class Student implements Comparable {
 String firstname, lastname;
 int StudentId;
 double GPA;
 public Student() {
  System.out.println("this is the unparamaterized constructor");
 }

 public Student(String firstname, String lastname, int StudentId, double GPA) {
  if (firstname == null || lastname == null || StudentId == 0 || GPA == 0.0) {
   throw new IllegalArgumentException();
  }
  this.firstname = firstname;
  this.lastname = lastname;
  this.StudentId = StudentId;
  this.GPA = GPA;
 }

 public String firstname() {
  return firstname;
 }

 public String lastname() {
  return lastname;
 }

 public int StudentId() {
  return StudentId;
 }

 public double GPA() {
  return GPA;
 }

 public int compareTo(Object o) {
  double f = GPA - ((Student) o).GPA;

  if (f == 0.0) {
   return 0;
  } else if (f < 0.0)
   return -1;
  else
   return 1;
 }
}

public class ComparableTest extends Student {
 public static void main(String a[]) {
  TreeSet free = new TreeSet();
  free.add(new Student("gaurav", "yadav", 26, 4.0));
  free.add(new Student("paras", "yadav", 34, 3.0));
  free.add(new Student("suman", "yadav", 65, 9.0));
  free.add(new Student("ram", "saxena", 67, 7.8));
  free.add(new Student("nitasha", "kuntal", 74, 7.9));
  Object[] free2 = free.toArray();
  Student s;
  for (Object obj: free2) {
   s = (Student) obj;
   System.out.printf("name=%s %s id=%d GPA=%.1f\n", s.firstname(), s.lastname(), s.StudentId(), s.GPA());
  }
 }
}

       
 

Determinant and Transpose of a square matrix using Java...

NOTE- Here matrix is input through a file.

here is the code .....


       

import java.io.*;
import java.util.*;
import static java.lang.Math.pow;

public class Read {


 static Scanner input = new Scanner(System.in);

 static int count = 0;
 public static void main(String[] args) throws IOException {
  String fileName = "test.txt";
  File file = new File("test.txt");
  BufferedReader be = new BufferedReader(new FileReader(file));
  String raw;
  while ((raw = be.readLine()) != null)
   count++;

  int[][] transpose = new int[count][count];
  int[][] matrix = new int[count][count];





  String line = "";

  FileInputStream inputStream = new FileInputStream(fileName);
  Scanner scanner = new Scanner(inputStream);
  DataInputStream in = new DataInputStream(inputStream);
  BufferedReader bf = new BufferedReader(new InputStreamReader( in ));

  int lineCount = 0;
  String[] numbers;
  while ((line = bf.readLine()) != null) {
   numbers = line.split(" ");
   for (int i = 0; i < 3; i++) {
    matrix[lineCount][i] = Integer.parseInt(numbers[i]);
   }

   lineCount++;
  }
  bf.close();
  System.out.println("The matrix is:");

  for (int i = 0; i < 3; i++) {
   for (int j = 0; j < 3; j++) {
    System.out.print(matrix[i][j] + " ");
   }
   System.out.println();
  }
  System.out.println();


  for (int k = 0; k < count; k++) {
   for (int k1 = 0; k1 < count; k1++) {
    transpose[k][k1] = matrix[k1][k];

   }
  }

  int i, j = 1, k = count - 1;
  double determinant = 0.0, p;
  for (i = 0; i < count; i++) {
   p = Math.pow(-1.0, i);
   if (i == count - 1)
    k = 1;
   determinant = determinant + (matrix[0][i] * (matrix[1][j] * matrix[2][k] - matrix[2][j] * matrix[1][k])) * p;
   j = 0;

  }
  System.out.println(determinant);

 }
}

       
 

Saturday, 27 July 2013

Source code for project developed in core Java " RAILWAY RESERVATION SYSTEM "

/*This is a java project source code for "RAILWAY RESERVATION MANAGEMENT SYSTEM" developed in core java technology */

 I thorougly tested the program myself and it works well ,after all if you need any  help then contact me my email is written above bbye ..
                                                                                      ------by gaurav kumar yadav


email:-gaurav10610@gmail.comif you like this code then you can subscribe me on facebook link:-

and subscribe my blog:-www.javaprogrammingstuff.blogspot.com


To download complete source code of the project click here.. DOWNLOAD


Thursday, 25 July 2013

Deterministic finite automata ( DFA ) implemented using Java....

 

This is a java program to simulate the DFA( deterministic finite automata ) developed using J2SE . It works for any general dfa that you have specified through five tuples during the execution of the program. 

To know that how to give input to the program please click here

here is the code  :-


       

import java.io.*;
import java.util.*;
public class Dfasimulator {

 public int[][] Transition = new int[20][20];
 public int alphaset, stateset;
 public ArrayList < Character > alphabet;
 public Set < Integer > finalstates;

 public void builtdfa() throws Exception {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("please enter the no. of alphabets in the alphabet set of DFA");
  alphaset = Integer.parseInt(br.readLine());
  //System.out.println(alphaset);
  System.out.println("please enter the no. of states in the set of DFA");
  stateset = Integer.parseInt(br.readLine());

  System.out.println("please enter all the alphabets of the DFA simultaneosly");
  String alphabets = br.readLine();

  alphabet = new ArrayList < Character > ();
  for (int i = 0; i < alphabets.length(); i++) {
   alphabet.add(alphabets.charAt(i));

  }
  //System.out.println(alphabet);

  for (int s = 0; s < stateset; s++) {
   System.out.println("enter the row entries of the transition table");
   for (int r = 0; r < alphaset; r++) {
    int int1 = Integer.parseInt(br.readLine());
    Transition[s][r] = int1;
   }
  }

  finalstates = new HashSet < Integer > ();
  System.out.println("please enter the final states of the DFA\n");
  System.out.println("when you are done of giving the inputs enter -2 to stop feeding final states");

  int int2 = Integer.parseInt(br.readLine());

  while (int2 != -2) {
   finalstates.add(int2);
   int2 = Integer.parseInt(br.readLine());
  }
  System.out.println(finalstates);
  DfaTest();
 }

 public void DfaTest() throws Exception {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  int state;
  System.out.println("enter the starting state");
  state = Integer.parseInt(br.readLine());

  System.out.println("give input to the DFA\n");
  System.out.println("end your input with # character\n");
  String input = br.readLine();
  int index = 0;

  while (input.charAt(index) != '#') {
   char char1 = input.charAt(index);
   int index1 = alphabet.indexOf(char1);
   state = Transition[state][index1];
   index++;
  }
  System.out.println("\nfinal state after giving the input is " + state);
  if (finalstates.contains(state))
   System.out.print("your input string is accepted by the DFA");
  else
   System.out.println("the input string is rejected by  the DFA");
 }

 public static void main(String args[]) throws Exception {
  Dfasimulator raw = new Dfasimulator();
  raw.builtdfa();
  //System.out.println(raw.alphaset);
 }
}

       
 

Monday, 1 July 2013

Encryption and Decryption of text documents using java...

This is a java program for decryption and encryption purpose of text documents it could be run everywhere and can be used to encrypt and decrypt such confidential text documents .

I use the concept of serialization and some mathematical algorithm to encrypt and decrypt the document.After encryption the program will generate a cipher text and a decryption key both of which are ".ser" files.

How to use :-1. If you are encrypting the text file then you have to give the path of that text document upto .txt extension like "D:\power.txt".

2. If you are decrypting the file then you have to give the path of the cipher text and the decryption key both of which are ".ser" files for example:- 

cipher Text - "d:\cipher.ser" 

decryption Key - "d:\key.ser"

You can use this program to extent your big projects.

algorithm of the code is here

here is the code....



       



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

public class Encrypt {

 int len;
 public double yo;
 public int[] key;
 static String str;
 static String data;
 public String cipherPath;
 public String plainPath;
 public String original1;
 public int[] cipher;
 public int[] c;
 public int[] d;
 public int[] plain1;
 public int[] plain2;
 public int[] ascii;
 public int[] plain;
 static char[] arrow;
 char[] original;

 /**
  * This function starts the encryption process
  * @param ascii contains ascii values of all the characters from the input file
  */
 public void Encryption_logic(int[] ascii) {
  c = new int[ascii.length / 2];
  d = new int[ascii.length / 2];
  if (ascii.length % 2 == 0) {
   for (int k = 0; k < ascii.length / 2; k++) {
    c[k] = ascii[k];
    c[k] = c[k] * (k + 2);
   }
   for (int f = 0; f < ascii.length / 2; f++) {
    d[f] = ascii[ascii.length / 2 + f];
    d[f] = d[f] * (f + 3);
   }
  }
  ciphertext(c, d);
 }

 /**
  * This function prepares the final cipher text(encrypted Text) and decryption key and writes it on to the persistent storage
  * @param c
  * @param d
  */
 public void ciphertext(int[] c, int[] d) {
  try {

   cipher = new int[c.length + d.length];

   for (int q = 0, l = 0, p = 0; q < c.length + d.length; q++) {

    if (q % 2 == 0 || q == 0) {
     cipher[q] = c[l];
     l++;
    }

    else {
     cipher[q] = d[p];
     p++;
    }
   }

   System.out
     .println("Please Enter The Location Where You Want To Save The Encrypted Cipher Text And The Encryption Key");
   BufferedReader br2 = new BufferedReader(new InputStreamReader(
     System.in));
   cipherPath = br2.readLine();
   FileOutputStream file2 = new FileOutputStream(cipherPath
     + "cipher.ser");
   ObjectOutputStream obj2 = new ObjectOutputStream(file2);
   obj2.writeObject(cipher);
   obj2.close();
   System.out
     .println("your encrypted text and key is saved to the location:- "
       + cipherPath);

   key = new int[5];
   key[0] = cipher[0] + cipher[cipher.length - 2];
   key[1] = d[0];
   key[2] = d[0] + c[0];
   key[3] = c[c.length - 1];
   key[4] = (cipher.length - 1);

   FileOutputStream file3 = new FileOutputStream(cipherPath
     + "key.ser");
   ObjectOutputStream obj3 = new ObjectOutputStream(file3);
   obj3.writeObject(key);
   obj3.close();

  } catch (Exception e) {
   System.out.println("\nexception caught");
  }
 }
 
/**
 * 
 * @param cipher is the array containing cipher text
 * @param key is the decryption key
 */
 public void decryption_logic(int[] cipher, int[] key) {
  try {
   plain1 = new int[cipher.length / 2];
   plain2 = new int[cipher.length / 2];

   if ((key[0] == (cipher[0] + cipher[cipher.length - 2]))
     && (key[4] == cipher.length - 1)
     && (key[2] == (cipher[0] + cipher[1]))
     && (key[1] == cipher[1])
     && (key[3] == cipher[cipher.length - 2])) {
    for (int p = 0, a = 0, z = 0; p < cipher.length; p++) {

     if (p % 2 == 0 || p == 0) {
      plain1[a] = cipher[p];
      plain1[a] = plain1[a] / (a + 2);
      a++;
     }

     else {
      plain2[z] = cipher[p];
      plain2[z] = plain2[z] / (z + 3);
      z++;
     }

    }
   }

   else {
    System.out.println("\ndecryption key is not valid");
   }

   plain = new int[plain1.length + plain2.length];
   for (int e = 0, b = 0; e < (plain1.length + plain2.length); e++) {
    if (e < plain1.length) {
     plain[e] = plain1[e];
    } else {
     plain[e] = plain2[b];
     b++;
    }
   }
   originalText(plain);
  } catch (Exception u) {
   u.printStackTrace();
  }
 }

 /**
  * This function will write the original text to the text file after decryption and store the file at user specified location
  * @param plain
  * @return
  */
 public char[] originalText(int[] plain) {
  try {
   if (plain[plain.length - 1] == '?') {
    original = new char[plain.length - 1];
    System.out.println("\n");

    for (int o = 0; o < (plain.length - 1); o++) {
     original[o] = (char) plain[o];
     // System.out.print(original[o]);
    }
   } else {
    original = new char[plain.length];
    System.out.println("\n");

    for (int o = 0; o < plain.length; o++) {
     original[o] = (char) plain[o];
     // System.out.print(original[o]);
    }
   }

   original1 = new String(original);
   // System.out.println(original1);
   System.out
     .println("\nPlease enter the location where you want to store the plain text after decryption \n");

   BufferedReader br4 = new BufferedReader(new InputStreamReader(
     System.in));
   plainPath = br4.readLine();
   File file4 = new File(plainPath + "plainText.txt");
   FileWriter fw = new FileWriter(file4);
   PrintWriter pw = new PrintWriter(fw);
   pw.write(original1);
   System.out.println("your plainText is stored at location :-"
     + plainPath);
   pw.flush();
   pw.close();
  } catch (Exception q) {
   q.printStackTrace();
  }
  return original;
 }
/**
 * initializing an integer array with the ascii values of the characters from @arrow
 * @param arrow
 */
 public void asciiarray(char[] arrow) {
  int j;
  ascii = new int[arrow.length];
  System.out.print("\n");
  for (j = 0; j < arrow.length; j++) {
   ascii[j] = arrow[j];
  }
  Encryption_logic(ascii);
 }
/**
 * 
 * Here '?' is added at the last index of string if its length is not even to make the algorithm work
 * and initializing a character array with characters from @data
 * @param data contains whole input file data
 */
 public void initial(String data) {
  int i;
  
  if (data.length() % 2 != 0) {
   arrow = new char[data.length() + 1];
   arrow[data.length()] = '?';
  } else {
   arrow = new char[data.length()];
  }
  for (i = 0; i < data.length(); i++) {
   arrow[i] = data.charAt(i);
  }
 }

 /**
  * This function will take the file to be encrypted and store its whole content in a single String object.
  * @return
  */
 public String inputData() {
  System.out
    .println("Please Enter The Address Of the File To Be Encrypted\n");
  try {
   BufferedReader br6 = new BufferedReader(new InputStreamReader(
     System.in));
   str = br6.readLine();
   String[] fileExtension=str.split("\\.");
   if(!fileExtension[1].equals("txt")){
    System.out.println("File to be encrypted is not a text file ...Plese try again");
   }
   
   File file = new File(str);
   FileReader file1 = new FileReader(file);
   BufferedReader br = new BufferedReader(file1);
   String line = null;
   StringBuilder sb = new StringBuilder();
   String is = System.getProperty("line.separator");
   while ((line = br.readLine()) != null) {
    sb.append(line);
    sb.append(is);
   }
   data = sb.toString();
   // System.out.println(data);
   br.close();

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

 public static void main(String args[]) {
  int choice;

  Encrypt ko = new Encrypt();
  try {
   BufferedReader br1 = new BufferedReader(new InputStreamReader(
     System.in));
   System.out
     .println("what you want to do ???encryption or decryption enter 1 for encryption and 2 for decryption \n");
   choice = Integer.parseInt(br1.readLine());

   switch (choice) {
   case 1:
    ko.inputData();
    ko.initial(data);
    ko.asciiarray(arrow);
    break;

   case 2:
    String encryptedPath;
    String keyPath;
    BufferedReader br5 = new BufferedReader(new InputStreamReader(
      System.in));
    System.out
      .println("please enter the location of the cipher text\n");
    encryptedPath = br5.readLine();
    System.out
      .println("please enter the location of the decryption key\n");
    keyPath = br5.readLine();

    FileInputStream file5 = new FileInputStream(encryptedPath);
    ObjectInputStream read = new ObjectInputStream(file5);
    int[] cipher1 = (int[]) read.readObject();

    FileInputStream file6 = new FileInputStream(keyPath);
    ObjectInputStream read1 = new ObjectInputStream(file6);
    int[] key1 = (int[]) read1.readObject();
    ko.decryption_logic(cipher1, key1);
    break;

   default:
    break;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}