Friday, 19 October 2012

how to make a copy of a button image from one layout to another layout using drag and drop in android programmatically


MainActivity.java

package com.example.draganddropdemo;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements OnTouchListener {

   private static final int START_DRAGGING = 0;
   private static final int STOP_DRAGGING = 1;
  
   private Button dragbtn1,dragbtn2;
   private RelativeLayout layout;
   private int status;
   private ViewGroup.LayoutParams params;
   private ImageView image;
  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println("------------onCreate-----------------------------------");
        layout =  (RelativeLayout) findViewById(R.id.frameLayout1);
       
        dragbtn1 = (Button) findViewById(R.id.drag_button);
        dragbtn1.setDrawingCacheEnabled(true);
        dragbtn1.setOnTouchListener(this);
       
        //dragbtn2 = (Button) findViewById(R.id.drag_button2);
        //dragbtn2.setDrawingCacheEnabled(true);
        //dragbtn2.setOnTouchListener(this);
       
        params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
       
    }

    @SuppressLint("NewApi") public boolean onTouch(View v, MotionEvent event) {
       
        System.out.println("------------onTouch-----------------------------------");
       
        if( event.getAction() == MotionEvent.ACTION_DOWN ) {
            status = START_DRAGGING;
            image = new ImageView(this);
            image.setImageBitmap(dragbtn1.getDrawingCache());
            layout.addView(image,params);
        }
        if( event.getAction() == MotionEvent.ACTION_UP ) {
            status = STOP_DRAGGING;
            Log.i("Drag", "Stopped Dragging");
        } else if( event.getAction() == MotionEvent.ACTION_MOVE ) {
            if( status == START_DRAGGING ) {
               
                System.out.println("--------------Dragging--------------");
                image.setPadding((int)event.getRawX()-20,(int)event.getRawY()-40, 0, 0);
                image.invalidate();
               
            }
        }
       
        return false;
    }

   
}

xml file - activity_main.xml 

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/frameLayout1"
        android:layout_width="300dp"
        android:layout_height="600dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:background="#008000" >

        <Button
            android:id="@+id/drag_button"
            android:layout_width="wrap_content"
            android:layout_height="70dp"
            android:background="#FF00FF"
            android:text="DragDrop" />

        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_marginBottom="134dp"
            android:background="#A52A2A" >
        </RelativeLayout>

        <Button
            android:id="@+id/drag_button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/relativeLayout1"
            android:text="DragButton2" />

    </RelativeLayout>

Thursday, 13 September 2012

Rating bar in Android and How to Save Ratingbar state in next time open that application


Ratingbar in Android Java.........

How to Save ratingbar state in next time open that app...........

Main Program : RatingbarMainActivit.java

package com.example.ratingbar;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class RatingbarMainActivity extends Activity {

    RatingBar ratingbarClick;
    Button sub_btn;
    TextView textRatingView , textRatingViewSave;
    Boolean val = true;
    float ans = (float) 0.0;
    //--------------------------------------------------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ratingbar_main);
       
        ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
        ratingbarClick.setOnRatingBarChangeListener(rateObj);
       
       
        SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences(RatingbarMainActivity.this);
        ans = sharePref.getFloat("Get_Rating", 0.0f);
        System.out.println("--------------------------------------ans = " + ans);
        if(val) {
            ratingbarClick.setRating(ans);
        }
        else {
            ratingbarClick.setRating(ans);
        }
       
        textRatingView = (TextView) findViewById(R.id.ratingView);
       

    }

    //--------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------
   
        RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
           
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
               
                //textRatingView.setText(String.valueOf(rating));
                ans = ratingbarClick.getRating();
               
                SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences(RatingbarMainActivity.this);
                SharedPreferences.Editor edit = sharePref.edit();
                edit.putFloat("Get_Rating", ans);
                edit.commit();
                val = false;
               
            }
        };

   
    //--------------------------------------------------------------------------------------------
   
}
Program 2 : activity_ratingbar_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ratingBar1"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="23dp"
        android:text="Select Your Rating Bar Here"
        tools:context=".RatingbarMainActivity" />
   
    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="63dp" />


    <TextView
        android:id="@+id/ratingView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ratingBar1"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="Click To Save Rating In TextBox" />

</RelativeLayout>

Thursday, 9 August 2012

how to create java class dynamically

Program:

package com.accordess.ca;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * A test class to test dynamic compilation API.
 *
 */
public class CompilerAPITest {
   
    final Logger logger = Logger.getLogger(CompilerAPITest.class.getName()) ;
   
    /**Java source code to be compiled dynamically*/
    static String sourceCode = "package com.accordess.ca;" +
        "class DynamicCompilationHelloWorld{" +
            "public static void main (String args[]){" +
                "System.out.println (\"Hello, dynamic compilation world!\");" +
            "}" +
        "}" ;
   
    /**
     * Does the required object initialization and compilation.
     */
    public void doCompilation (){
       
        /*Creating dynamic java source code file object*/
        SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject ("com.accordess.ca.DynamicCompilationHelloWorld", sourceCode) ;
        JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;
       
        /*Instantiating the java compiler*/
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
       
        /**
         * Retrieving the standard file manager from compiler object, which is used to provide
         * basic building block for customizing how a compiler reads and writes to files.
         *
         * The same file manager can be reopened for another compiler task.
         * Thus we reduce the overhead of scanning through file system and jar files each time
         */
       
        StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
       
       
       
        /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);
       
        /*Prepare any compilation options to be used during compilation*/
        //In this example, we are asking the compiler to place the output files under bin folder.
       
        String[] compileOptions = new String[]{"-d", "bin"} ;
        Iterable<String> compilationOptionss = Arrays.asList(compileOptions);
       
        /*Create a diagnostic controller, which holds the compilation problems*/
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
       
        /*Create a compilation task from compiler by passing in the required input objects prepared above*/
        CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptionss, null, compilationUnits) ;
       
        //Perform the compilation by calling the call method on compilerTask object.
        boolean status = compilerTask.call();
       
        if (!status){//If compilation error occurs
            /*Iterate through each compilation problem and print it*/
            for (Diagnostic diagnostic : diagnostics.getDiagnostics()){
                System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
            }
        }
        try {
            stdFileManager.close() ;//Close the file manager
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String args[]){
        new CompilerAPITest().doCompilation() ;
    }

}

/**
 * Creates a dynamic source code file object
 *
 * This is an example of how we can prepare a dynamic java source code for compilation.
 * This class reads the java code from a string and prepares a JavaFileObject
 *
 */
class DynamicJavaSourceCodeObject extends SimpleJavaFileObject{
    private String qualifiedName ;
    private String sourceCode ;
   
    /**
     * Converts the name to an URI, as that is the format expected by JavaFileObject
     *
     *
     * @param fully qualified name given to the class file
     * @param code the source code string
     */
    protected DynamicJavaSourceCodeObject(String name, String code) {
        super(URI.create("string:///" +name.replaceAll(".", "/") + Kind.SOURCE.extension), Kind.SOURCE);
        this.qualifiedName = name ;
        this.sourceCode = code ;
    }
   
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors)
            throws IOException {
        return sourceCode ;
    }

    public String getQualifiedName() {
        return qualifiedName;
    }

    public void setQualifiedName(String qualifiedName) {
        this.qualifiedName = qualifiedName;
    }

    public String getSourceCode() {
        return sourceCode;
    }

    public void setSourceCode(String sourceCode) {
        this.sourceCode = sourceCode;
    }
}

Thanks to www.javaworld.com

Wednesday, 8 August 2012

how to use map.entry in java example

Here,How to split  HashMap values  using Map and set interface..........

//package OtherHashMapExamples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class MapUsageExample {

    public static void main(String[] args) {
       
        HashMap hm = new HashMap();
       
        hm.put("Hari" , new Integer(50));
        hm.put(" Kumar", new Integer(30));
        hm.put("Daya", new Integer(60));
        //hm.put("Krishnan", new Integer(70));
       
        Set set = hm.entrySet();
        //System.out.println(" hm.entrySet() : " + set);
       
        Iterator it = set.iterator();
       
        while(it.hasNext()) {
       
            //System.out.println("it Values :  " + it.next());
            Map.Entry<String, Integer> mapMe = (Map.Entry) it.next();
           
            System.out.println(" Mapped Values from Iterator Key : " + mapMe.getKey());
            System.out.println(" Mapped Values from Iterator Values : " + mapMe.getValue());
           
           
        }
        int addValue =  ((Integer) hm.get("Hari")).intValue();
        hm.put("Hari",new Integer(addValue + 450));
        System.out.println( " Hari new Name is : " + hm.get("Hari"));
       

    }

}

Example Program for using ArrayList and Comparator in java Collections and their Methods

Java Object Sorting using Comparator vs Comparable interface Class.
Java Sorting Comparator vs Comparable interface .
Here we are using for Collections Methods  for Sorting Purpose. and ArrayList for Storing Purpose.....
Write a java program to use the Comparator  and Comparable interface in Java.....
(1) Employee.java

package ComparatorVsComparable;

import java.util.Comparator;


public class Employee   {

    private String empNameId;
    private int empAge;
   
    public Employee() {
       
    }
   
    Employee(String empNameId , int empAge) {
   
       
        this.empNameId = empNameId ;
        this.empAge    = empAge ;
       
    }
   
    public String getName() {
       
        return empNameId;
    }
    public void setName(String empNameId) {
       
        this.empNameId = empNameId;
       
    }
    public int getAge() {
       
        return empAge;
    }
    public void setAge(int empAge) {
       
        this.empAge = empAge;
    }
   
   
}

(2)CompareClassOnly.java
package ComparatorVsComparable;

import java.util.Comparator;

public class CompareClassOnly implements Comparator<Employee> {


   
    @Override
    public int compare(Employee emp1, Employee emp2) { // Compare Numbers
       
        System.out.println(" -----------CompareClassOnly Class Executed with Compare Method -----------");
               
        return emp1.getAge() > emp2.getAge() ? -1 : (emp1.getAge() == emp2.getAge() ? 0 : 1 );
    }

}

(3)CompareStringOnly.java

package ComparatorVsComparable;

import java.util.Comparator;

public class CompareStringOnly implements Comparator<Employee>{

    @Override
    public int compare(Employee o1, Employee o2) {
      
        System.out.println(" -----------CompareStringOnly Class Executed with Compare Method -----------");
      
        String str1 = o1.getName();
        String str2 = o2.getName();
      
        return str1.compareTo(str2);
    }

   
   
   
}
(4) ComparatorMainClass.java

package ComparatorVsComparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;



public class ComparatorMainClass {
   
    public static void main(String args[]) {
      
        List<Employee> list = new ArrayList<Employee>();
      
        list.add(new Employee("Hari581", 24));
        list.add(new Employee("Dayanidhi582", 23));
        list.add(new Employee("Athik111", 22));
        list.add(new Employee("Premkumar486", 28));
        list.add(new Employee("Muthu420", 27));
      
        Collections.sort(list , new CompareStringOnly());
        System.out.println(" \n After Collection Default Descending Sorting NameWise Order Details : ");
        for(Employee e : list) {
          
            System.out.println(" EmpNameId : " +e.getName()+"      EmpAge : " + e.getAge());
        }
      
      
        Collections.sort(list , new CompareClassOnly());
        System.out.println(" \n After Collection Default Descending Sorting AgeWise Order Details : ");
        for(Employee e : list) {
          
            System.out.println(" EmpNameId : " +e.getName()+"      EmpAge : " + e.getAge());
        }
      
    }

}


In This Example used to Find the Given Name with Age for Sorting Purpose..
First Sort with Name Wise ( String Sorting )
Second Sort With Age Wise ( Number Sorting)

output::

 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------

 After Collection Default Descending Sorting NameWise Order Details :
 EmpNameId : Athik111      EmpAge : 22
 EmpNameId : Dayanidhi582      EmpAge : 23
 EmpNameId : Hari581      EmpAge : 24
 EmpNameId : Muthu420      EmpAge : 27
 EmpNameId : Premkumar486      EmpAge : 28
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------

 After Collection Default Descending Sorting AgeWise Order Details :
 EmpNameId : Premkumar486      EmpAge : 28
 EmpNameId : Muthu420      EmpAge : 27
 EmpNameId : Hari581      EmpAge : 24
 EmpNameId : Dayanidhi582      EmpAge : 23
 EmpNameId : Athik111      EmpAge : 22

Note:: This Program is for mm Own Code.. If you have any Query pls mail to:  vhkrishnan.v@gmail.com

Wednesday, 1 August 2012

why java is not fully or completely oops langauge?

Java is a OOP language and it is not a pure Object Based Programming Language.

Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
  1. Encapsulation/Data Hiding
  2. Inheritance
  3. Polymorphism
  4. Abstraction
  5. All predefined types are objects
  6. All operations are performed by sending messages to objects
  7. All user defined types are objects.

Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects.

Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

Which language is fully object oriented language and how ?

OOP languages

Simula (1967) is generally accepted as the first language to have the primary features of an object-oriented language. It was created for making simulation programs, in which what came to be called objects were the most important information representation. Smalltalk (1972 to 1980) is arguably the canonical example, and the one with which much of the theory of object-oriented programming was developed. Concerning the degree of object orientation, the following distinctions can be made:
  • Languages called "pure" OO languages, because everything in them is treated consistently as an object, from primitives such as characters and punctuation, all the way up to whole classes, prototypes, blocks, modules, etc. They were designed specifically to facilitate, even enforce, OO methods. Examples: Eiffel, Emerald.[19], JADE, Obix, Scala, Smalltalk
  • Languages designed mainly for OO programming, but with some procedural elements. Examples: C++, Java, C#, VB.NET, Python.
  • Languages that are historically procedural languages, but have been extended with some OO features. Examples: Visual Basic (derived from BASIC), Fortran, Perl, COBOL 2002, PHP, ABAP.
  • Languages with most of the features of objects (classes, methods, inheritance, reusability), but in a distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2) and Common Lisp.
  • Languages with abstract data type support, but not all features of object-orientation, sometimes called object-based languages. Examples: Modula-2 (with excellent encapsulation and information hiding), Pliant, CLU.

 

Monday, 14 May 2012

how to make a tetris game in flash as3

Creation of a complete Flash Tetris game in AS 3.0

Build an AS3 Tetris Game from Junior AS3.0 Developer



First Create a Fla File with the size of 400*480 pixel stage height width. and set background color with black.

then create a As3 class Main Document File and save it in same folder :

package
{

    import flash.display.Sprite;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.events.KeyboardEvent;


    public class Main extends Sprite
    {
        private const TS:uint = 24;
        private var fieldArray:Array;
        private var fieldSprite:Sprite;
        private var tetrominoes:Array = new Array();
        private var colors:Array = new Array();
        private var tetromino:Sprite;
        private var currentTetromino:uint;
        private var nextTetromino:uint;
        private var currentRotation:uint;
        private var tRow:int;
        private var tCol:int;
        private var timeCount:Timer = new Timer(500);
        private var gameOver:Boolean = false;

        public function Main()
        {
            generateField();
            initTetrominoes();
            nextTetromino = Math.floor(Math.random() * 7);
            generateTetromino();
            stage.addEventListener(KeyboardEvent.KEY_DOWN,onKDown);
        }
        private function generateField():void
        {
            var colors:Array = new Array("0x444444","0x555555");
            fieldArray = new Array();
            fieldSprite = new Sprite();
            addChild(fieldSprite);
            fieldSprite.graphics.lineStyle(0,0x000000);
            for (var i=0; i<20; i++)
            {
                fieldArray[i] = new Array();
                for (var j=0; j<10; j++)
                {
                    fieldArray[i][j] = 0;
                    fieldSprite.graphics.beginFill(colors[(j%2+i%2)%2]);
                    fieldSprite.graphics.drawRect(TS*j,TS*i,TS,TS);
                    fieldSprite.graphics.endFill();
                }
            }

        }
        private function initTetrominoes():void
        {
            // I
            tetrominoes[0]=[[[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]],
            [[0,1,0,0],[0,1,0,0],[0,1,0,0],[0,1,0,0]]];
            colors[0] = 0x00FFFF;
            // T
            tetrominoes[1]=[[[0,0,0,0],[1,1,1,0],[0,1,0,0],[0,0,0,0]],
            [[0,1,0,0],[1,1,0,0],[0,1,0,0],[0,0,0,0]],
            [[0,1,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]],
            [[0,1,0,0],[0,1,1,0],[0,1,0,0],[0,0,0,0]]];
            colors[1] = 0x767676;
            // L
            tetrominoes[2]=[[[0,0,0,0],[1,1,1,0],[1,0,0,0],[0,0,0,0]],
            [[1,1,0,0],[0,1,0,0],[0,1,0,0],[0,0,0,0]],
            [[0,0,1,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]],
            [[0,1,0,0],[0,1,0,0],[0,1,1,0],[0,0,0,0]]];
            colors[2] = 0xFFA500;
            // J
            tetrominoes[3]=[[[1,0,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0]],
            [[0,1,1,0],[0,1,0,0],[0,1,0,0],[0,0,0,0]],
            [[0,0,0,0],[1,1,1,0],[0,0,1,0],[0,0,0,0]],
            [[0,1,0,0],[0,1,0,0],[1,1,0,0],[0,0,0,0]]];
            colors[3] = 0x0000FF;
            // Z
            tetrominoes[4]=[[[0,0,0,0],[1,1,0,0],[0,1,1,0],[0,0,0,0]],
            [[0,0,1,0],[0,1,1,0],[0,1,0,0],[0,0,0,0]]];
            colors[4] = 0xFF0000;
            // S
            tetrominoes[5]=[[[0,0,0,0],[0,1,1,0],[1,1,0,0],[0,0,0,0]],
            [[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]];
            colors[5] = 0x00FF00;
            // O
            tetrominoes[6] = [[[0,1,1,0],[0,1,1,0],[0,0,0,0],[0,0,0,0]]];
            colors[6] = 0xFFFF00;
        }
        private function generateTetromino():void
        {
            if (! gameOver)
            {
                currentTetromino = nextTetromino;
                nextTetromino = Math.floor(Math.random() * 7);
                drawNext();
                //currentTetromino = Math.floor(Math.random() * 7);
                currentRotation = 0;
                tRow = 0;
                if (tetrominoes[currentTetromino][0][0].indexOf(1) == -1)
                {
                    tRow = -1;
                }
                tCol = 3;
                drawTetromino();
                if (canFit(tRow,tCol,currentRotation))
                {
                    timeCount.addEventListener(TimerEvent.TIMER, onTime);
                    timeCount.start();
                }
                else
                {
                    gameOver = true;
                }
               
            }

        }
        private function drawTetromino():void
        {
            var ct:uint = currentTetromino;
            tetromino=new Sprite();
            addChild(tetromino);
            tetromino.graphics.lineStyle(0,0x000000);
            for (var i:int=0; i<tetrominoes[ct][currentRotation].length; i++)
            {
                for (var j:int=0; j<tetrominoes[ct][currentRotation][i].length; j++)
                {
                    if (tetrominoes[ct][currentRotation][i][j] == 1)
                    {
                        tetromino.graphics.beginFill(colors[ct]);
                        tetromino.graphics.drawRect(TS*j,TS*i,TS,TS);
                        tetromino.graphics.endFill();
                    }
                }
            }
            placeTetromino();
        }
        private function placeTetromino():void
        {
            tetromino.x = tCol * TS;
            tetromino.y = tRow * TS;
        }
        private function onKDown(e:KeyboardEvent):void
        {
            if (! gameOver)
            {
                switch (e.keyCode)
                {
                    case 37 :
                        if (canFit(tRow,tCol - 1,currentRotation))
                        {
                            tCol--;
                            placeTetromino();
                        }
                        break;
                    case 38 :
                        var ct:uint = currentRotation;
                        var rot:uint = (ct + 1) % tetrominoes[currentTetromino].length;
                        if (canFit(tRow,tCol,rot))
                        {
                            currentRotation = rot;
                            removeChild(tetromino);
                            drawTetromino();
                            placeTetromino();
                        }
                        break;
                    case 39 :
                        if (canFit(tRow,tCol + 1,currentRotation))
                        {
                            tCol++;
                            placeTetromino();
                        }
                        break;
                    case 40 :
                        if (canFit(tRow+1,tCol,currentRotation))
                        {
                            tRow++;
                            placeTetromino();
                        }
                        else
                        {
                            landTetromino();
                            generateTetromino();
                        }
                        break;
                }
            }
        }

        private function canFit(row:int,col:int,side:uint):Boolean
        {
            var ct:uint = currentTetromino;
            for (var i:int=0; i<tetrominoes[ct][side].length; i++)
            {
                for (var j:int=0; j<tetrominoes[ct][side][i].length; j++)
                {
                    if (tetrominoes[ct][side][i][j] == 1)
                    {
                        // out of left boundary
                        if (col+j<0)
                        {
                            return false;
                        }
                        // out of right boundary
                        if (col+j>9)
                        {
                            return false;
                        }
                        if (row+i>19)
                        {
                            return false;
                        }
                        if (fieldArray[row + i][col + j] == 1)
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        private function landTetromino():void
        {
            var ct:uint = currentTetromino;
            var landed:Sprite;
            for (var i:int=0; i<tetrominoes[ct][currentRotation].length; i++)
            {
                for (var j:int=0; j<tetrominoes[ct][currentRotation][i].length; j++)
                {
                    if (tetrominoes[ct][currentRotation][i][j] == 1)
                    {
                        landed = new Sprite();
                        addChild(landed);
                        landed.graphics.lineStyle(0,0x000000);
                        landed.graphics.beginFill(colors[currentTetromino]);
                        landed.graphics.drawRect(TS*(tCol+j),TS*(tRow+i),TS,TS);
                        landed.graphics.endFill();
                        landed.name = "r" + (tRow + i) + "c" + (tCol + j);
                        fieldArray[tRow + i][tCol + j] = 1;
                    }
                }
            }
            removeChild(tetromino);
            timeCount.removeEventListener(TimerEvent.TIMER, onTime);
            timeCount.stop();
            checkForLines();
        }
        private function checkForLines():void
        {
            for (var i:int=0; i<20; i++)
            {
                if (fieldArray[i].indexOf(0) == -1)
                {
                    for (var j:int=0; j<10; j++)
                    {
                        fieldArray[i][j] = 0;
                        removeChild(getChildByName("r"+i+"c"+j));
                    }
                    for (j=i; j>=0; j--)
                    {
                        for (var k:int=0; k<10; k++)
                        {
                            if (fieldArray[j][k] == 1)
                            {
                                fieldArray[j][k] = 0;
                                fieldArray[j + 1][k] = 1;
                                getChildByName("r"+j+"c"+k).y+=TS;
                                getChildByName("r"+j+"c"+k).name="r"+(j+1)+"c"+k;
                            }
                        }
                    }

                }
            }
        }
        private function onTime(e:TimerEvent):void
        {
            if (canFit(tRow+1,tCol,currentRotation))
            {
                tRow++;
                placeTetromino();
            }
            else
            {
                landTetromino();
                generateTetromino();
            }
        }
        private function drawNext():void
        {
            if (getChildByName("next")!=null)
            {
                removeChild(getChildByName("next"));
            }
            var next_t:Sprite=new Sprite();
            next_t.x = 300;
            next_t.name = "next";
            addChild(next_t);
            next_t.graphics.lineStyle(0,0x000000);
            for (var i:int=0; i<tetrominoes[nextTetromino][0].length; i++)
            {
                for (var j:int=0; j<tetrominoes[nextTetromino][0][i].length; j++)
                {
                    if (tetrominoes[nextTetromino][0][i][j] == 1)
                    {
                        next_t.graphics.beginFill(colors[nextTetromino]);
                        next_t.graphics.drawRect(TS*j,TS*i,TS,TS);
                        next_t.graphics.endFill();
                    }
                }
            }
        }
    }
}

Monday, 19 September 2011

Swap Numbers Without Using Third Variable Java Example

Swap Numbers Without Using Third Variable Java Example

  1. /*
  2. Swap Numbers Without Using Third Variable Java Example
  3. This Swap Numbers Java Example shows how to
  4. swap value of two numbers without using third variable using java.
  5. */
  6.  
  7. public class SwapElementsWithoutThirdVariableExample {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. int num1 = 10;
  12. int num2 = 20;
  13.  
  14. System.out.println("Before Swapping");
  15. System.out.println("Value of num1 is :" + num1);
  16. System.out.println("Value of num2 is :" +num2);
  17.  
  18. //add both the numbers and assign it to first
  19. num1 = num1 + num2;
  20. num2 = num1 - num2;
  21. num1 = num1 - num2;
  22.  
  23. System.out.println("Before Swapping");
  24. System.out.println("Value of num1 is :" + num1);
  25. System.out.println("Value of num2 is :" +num2);
  26. }
  27.  
  28.  
  29. }
  30.  
  31. /*
  32. Output of Swap Numbers Without Using Third Variable example would be
  33. Before Swapping
  34. Value of num1 is :10
  35. Value of num2 is :20
  36. Before Swapping
  37. Value of num1 is :20
  38. Value of num2 is :10
  39. */

Swap Numbers Without Using Third Variable Java Example

Swap Numbers Without Using Third Variable Java Example

  1. /*
  2. Swap Numbers Without Using Third Variable Java Example
  3. This Swap Numbers Java Example shows how to
  4. swap value of two numbers without using third variable using java.
  5. */
  6. public class SwapElementsWithoutThirdVariableExample {
  7. public static void main(String[] args) {
  8. int num1 = 10;
  9. int num2 = 20;
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of num1 is :" + num1);
  12. System.out.println("Value of num2 is :" +num2);
  13. //add both the numbers and assign it to first
  14. num1 = num1 + num2;
  15. num2 = num1 - num2;
  16. num1 = num1 - num2;
  17. System.out.println("Before Swapping");
  18. System.out.println("Value of num1 is :" + num1);
  19. System.out.println("Value of num2 is :" +num2);
  20. }
  21. }
  22. /*
  23. Output of Swap Numbers Without Using Third Variable example would be
  24. Before Swapping
  25. Value of num1 is :10
  26. Value of num2 is :20
  27. Before Swapping
  28. Value of num1 is :20
  29. Value of num2 is :10
  30. */

Reverse Number using Java

Reverse Number using Java

  1. /*
  2.   Reverse Number using Java
  3.   This Java Reverse Number Example shows how to reverse a given number.
  4. */
  5.  
  6. public class ReverseNumber {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. //original number
  11. int number = 1234;
  12. int reversedNumber = 0;
  13. int temp = 0;
  14.  
  15. while(number > 0){
  16.  
  17. //use modulus operator to strip off the last digit
  18. temp = number%10;
  19.  
  20. //create the reversed number
  21. reversedNumber = reversedNumber * 10 + temp;
  22. number = number/10;
  23.  
  24. }
  25.  
  26. //output the reversed number
  27. System.out.println("Reversed Number is: " + reversedNumber);
  28. }
  29. }
  30.  
  31. /*
  32. Output of this Number Reverse program would be
  33. Reversed Number is: 4321
  34. */

Java Factorial Using Recursion Example

Java Factorial Using Recursion Example

Submitted By: Mohit Garg

  1. /*
  2. Java Factorial Using Recursion Example
  3. This Java example shows how to generate factorial of a given number
  4. using recursive function.
  5. */
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10.  
  11. public class JavaFactorialUsingRecursion {
  12.  
  13. public static void main(String args[]) throws NumberFormatException, IOException{
  14.  
  15. System.out.println("Enter the number: ");
  16.  
  17. //get input from the user
  18. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  19. int a = Integer.parseInt(br.readLine());
  20.  
  21. //call the recursive function to generate factorial
  22. int result= fact(a);
  23.  
  24.  
  25. System.out.println("Factorial of the number is: " + result);
  26. }
  27.  
  28. static int fact(int b)
  29. {
  30. if(b <= 1)
  31. //if the number is 1 then return 1
  32. return 1;
  33. else
  34. //else call the same function with the value - 1
  35. return b * fact(b-1);
  36. }
  37. }
  38.  
  39. /*
  40. Output of this Java example would be
  41.  
  42. Enter the number:
  43. 5
  44. Factorial of the number is: 120
  45. */

Java Interface example

Java Interface example

  1. /*
  2. Java Interface example.
  3. This Java Interface example describes how interface is defined and
  4. being used in Java language.
  5.  
  6. Syntax of defining java interface is,
  7. <modifier> interface <interface-name>{
  8.   //members and methods()
  9. }
  10. */
  11.  
  12. //declare an interface
  13. interface IntExample{
  14.  
  15. /*
  16.   Syntax to declare method in java interface is,
  17.   <modifier> <return-type> methodName(<optional-parameters>);
  18.   IMPORTANT : Methods declared in the interface are implicitly public and abstract.
  19.   */
  20.  
  21. public void sayHello();
  22. }
  23. }
  24. /*
  25. Classes are extended while interfaces are implemented.
  26. To implement an interface use implements keyword.
  27. IMPORTANT : A class can extend only one other class, while it
  28. can implement n number of interfaces.
  29. */
  30.  
  31. public class JavaInterfaceExample implements IntExample{
  32. /*
  33.   We have to define the method declared in implemented interface,
  34.   or else we have to declare the implementing class as abstract class.
  35.   */
  36.  
  37. public void sayHello(){
  38. System.out.println("Hello Visitor !");
  39. }
  40.  
  41. public static void main(String args[]){
  42. //create object of the class
  43. JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
  44. //invoke sayHello(), declared in IntExample interface.
  45. javaInterfaceExample.sayHello();
  46. }
  47. }
  48.  
  49. /*
  50. OUTPUT of the above given Java Interface example would be :
  51. Hello Visitor !
  52. */

Find Largest and Smallest Number in an Array Example

Find Largest and Smallest Number in an Array Example

  1. /*
  2.   Find Largest and Smallest Number in an Array Example
  3.   This Java Example shows how to find largest and smallest number in an
  4.   array.
  5. */
  6. public class FindLargestSmallestNumber {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. //array of 10 numbers
  11. int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
  12.  
  13. //assign first element of an array to largest and smallest
  14. int smallest = numbers[0];
  15. int largetst = numbers[0];
  16.  
  17. for(int i=1; i< numbers.length; i++)
  18. {
  19. if(numbers[i] > largetst)
  20. largetst = numbers[i];
  21. else if (numbers[i] < smallest)
  22. smallest = numbers[i];
  23.  
  24. }
  25.  
  26. System.out.println("Largest Number is : " + largetst);
  27. System.out.println("Smallest Number is : " + smallest);
  28. }
  29. }
  30.  
  31. /*
  32. Output of this program would be
  33. Largest Number is : 98
  34. Smallest Number is : 23
  35. */

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com