Showing posts with label abstract class java. Show all posts
Showing posts with label abstract class java. Show all posts

April 21, 2020

Making Tic Tac Toe using abstract and interface in Java Full source code


What we did here is, using the OOPs concepts abstract and interface we change the face of the project
Help us to do simple modification in future so as to add new games using the same matrix.
You have to go through the previous tutorials to fully understand the concepts.


Change in Tic Tac Toe class

public class TicTacToe implements IGame

Changes in Main class


import com.cfed.matrix.tictactoe.IGame;

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
 *
 */

/**
 * @author konzernites
 * @since 1.0
 *
 */
public class Main extends AbstractGame {

private static final long serialVersionUID = 8683452581122892182L;

/**
* @param args
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException {

Main mainClass = new Main();
mainClass.execute();

}

private void execute() throws IllegalAccessException {
Matrix<Character> matrix = new Matrix<>(3, 3);

System.out.println(" **** INSTRUCTIONS **** ");
System.out.println(" User has to enter row and column ");
System.out.println(" Postion starts from (0,0) to (2,2) ");

IGame game = new TicTacToe(matrix);
TicTacToe.isTwoPlayer = true;
playGame(game);

System.out.println(" ***** GAME OVER ***** ");
System.out.println(" Developed by consumerfed I T Section ");

}

}

AbstractGame.java


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
 *
 */

import com.cfed.matrix.tictactoe.IGame;

/**
 *
 */

/**
 * @author Konzernites
 *
 */
public abstract class AbstractGame {

public void playGame(IGame game) throws IllegalAccessException {
game.startGame();
}

}


IGame Interface in java


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
 *
 */
/**
 * 
 */
package com.cfed.matrix.tictactoe;

/**
 * @author jwalian walla bag
 *
 */
public interface IGame {
public void startGame() throws IllegalAccessException;

}





April 07, 2020

Tic Tac Toe - Play with computer | Full Java source code

ComputerMove.java

You will get a null pointer exception in tic tac toe game, for the java code which we posted earlier.
So these changes has to be made in the code.
While the user chose the first move other than the centre position, the Nullpointer Exception comes.

private Matrix<Character> generateFirstCompMove() throws IllegalAccessException {
int row = 1;
int col = 1;

if(matrix.isElementExist(row, col)) {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix.add(row, col, TikTocToe.COMP_MOVE);

}else {
matrix.add(1, 1, TikTocToe.COMP_MOVE);
}

return matrix;
}

September 14, 2019

Squaring and Sorting an input array contains negative and positive number

Questions asked in hackerearth and codeforgeeks


/**
 * Squaring and Sorting an input array contains negative and positive number
 *
 * Complexity O(2n)
 *
 */
package com.konzerntech.kozhikode;

import java.util.Arrays;

/**
 * @author Consumerfed Information Technology Section kozhikode
 * +91 8281 8080 29
 */
public class SquareAndSort {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int[] input = { -10, -8, -3, -1, 4, 6, 8 };
int len = input.length;
int[] output = new int[len];

int[] a = new int[len];
int[] b = new int[len];

int aLen = 0;
int bLen = 0;

for (int i = 0; i < len; i++) {
int value = input[i];
int square = value * value;
if (value < 0) {
a[aLen] = square;
aLen++;
} else {
b[bLen] = square;
bLen++;
}
}


int aPtr = aLen-1;
int bPtr = 0;


for (int i = 0; i < len; i++) {

if (bPtr > (bLen - 1)) {
while (aPtr >= 0) {
output[i] = a[aPtr];
i++;
aPtr--;
}
break;
}

if (aPtr < 0) {
while (bPtr < bLen) {
output[i] = b[bPtr];
i++;
bPtr++;
}
break;
}

if (b[bPtr] < a[aPtr]) {
output[i] = b[bPtr];
bPtr++;
} else {
output[i] = a[aPtr];
aPtr--;
}

}
System.out.println("Input : "+Arrays.toString(input));
System.out.println("Output : "+Arrays.toString(output));

}

}

Output


Input : [-10, -8, -3, -1, 4, 6, 8]
Output : [1, 9, 16, 36, 64, 64, 100]

Description :


Squaring and Sorting is petty tricky problem.
The array may contains both negative as well as positive integer values, so while square the array the output may not be a sorted one.
So what we did here is we divided the input array into two based on the negative and positive values after squaring it.
Then we compare the two array n th position of one array to the zero th position of the other to find the minimum value, thus found minimum value is inserted into output array.
we used pointer to point each elements in array.

December 24, 2018

Abstract class in java - explained in very simple way with an example

Abstract class in java

Abstract class as the name implies its an abstract.

The class which is not implemented, So we cannot create the object of that class.

Abstract class contains abstract as well as non abstract methods.

we can have abstract class with out abstract method.

you can even have abstract class with final method.

if you doesnt want to implement abstract method in sub class, make the sub class as abstract.

For Example let us consider animal as our abstract class. I wrote two funtion in it

lifeSpan();

isReproduce(); Let it be always "yes".


lifeSpan(); is an abstract method , which is different for each animals

now consider sub class as dog , cat and ant

these class extends that abstract class. The relation ship will come in this way like dog is an animal, cat is a animal ..."is - a" relation ship
since the sub class extends the base class animal.. we need to define lifespan() function in each subclass.

lifespan() is different for each animal

if i create an object Animal a = new dog();

a.isReproduce() ---->  "yes"
a.lifespan() -----> 13


Program



/**
 *  The study of behavior of animal is called ethology
 */
package com.cfed.oopsconcepts;

public abstract class Animal {

public String color;

    public abstract int lifeSpan();
 
    public void isReproduce() {
    System.out.println(" YES ");
    }

}



package com.cfed.oopsconcepts;

public class Dog extends Animal {

@Override
public int lifeSpan() {
// TODO Auto-generated method stub
return 13;
}
}


/**
 * 
 */
package com.cfed.oopsconcepts;

/**
 * @author Konzern
 *
 */
public class Cat extends Animal {

/* (non-Javadoc)
* @see com.cfed.oopsconcepts.Animal#lifeSpan()
*/
@Override
public int lifeSpan() {
// TODO Auto-generated method stub
return 16;
}
/**
* This method cannot access through super class
* as the method is not declared in the super class
*/
public void bark() {
System.out.println(" meow");
}

}


/**
 * 
 */
package com.cfed.oopsconcepts;

/**
 * @author konzern
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal animal = new Dog();
System.out.println(" Dog ");
animal.isReproduce();
System.out.println(animal.lifeSpan());
animal = new Cat();
System.out.println(" Cat ");
animal.isReproduce();
System.out.println(animal.lifeSpan());
//animal.bark(); 

}

}


Output



 Dog
 YES
13
 Cat
 YES
16






Prepare for java certification



October 15, 2013

Sending screenshot from client to Server through socket in java


How to send screen shot from client to server automatically in java

Did you ever think of getting screen shot from all computers in a network to a server. This code will helps you to do so....This code will capture the current desktop screen shot and sent it to server computer. This application is very useful to network administrator to track what other are doing in the computer at your organization.

ClientApp.java : is a client program that takes screen shot in regular interval.  The sendScreen function will help you to know how java program takes screen shot at intervals and sends to server machine. Here i used ImageIO class to create image buffer. There are other options too... The file is sent through a socket. the port number i used here is 1729. Server Name here used is loop back ip, where you need to specify the server computer name or ip  address.

On the Other hand
SeverApp.java will always listen to the port 1729. if any request comes there, it will catch request and save to the folder 


ClientApp.java


import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.imageio.ImageIO;


/**
 * @author lou reed
 *
 */
public class ClientApp implements Runnable {

    private static long nextTime = 0;
    private static ClientApp clientApp = null;
    private String serverName = "127.0.0.1"; //loop back ip
    private int portNo = 1729;
    //private Socket serverSocket = null;
   
    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        clientApp = new ClientApp();
        clientApp.getNextFreq();
        Thread thread = new Thread(clientApp);
        thread.start();
    }

    private void getNextFreq() {
        long currentTime = System.currentTimeMillis();
        Random random = new Random();
        long value = random.nextInt(180000); //1800000
        nextTime = currentTime + value;
        //return currentTime+value;
    }

    @Override
    public void run() {
        while(true){
            if(nextTime < System.currentTimeMillis()){
                System.out.println(" get screen shot ");
                try {
                    clientApp.sendScreen();
                    clientApp.getNextFreq();
                } catch (AWTException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(Exception e){
                    e.printStackTrace();
                }
               
            }
            //System.out.println(" statrted ....");
        }
       
    }

    private void sendScreen()throws AWTException, IOException {
           Socket serverSocket = new Socket(serverName, portNo);
             Toolkit toolkit = Toolkit.getDefaultToolkit();
             Dimension dimensions = toolkit.getScreenSize();
                 Robot robot = new Robot();  // Robot class
                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                 serverSocket.close();
    }
}




March 09, 2012

Reflection example in java


Example for reflection in java

Reflection in java makes it possible to inspect and call classes, methods, attributes etc dynamically at run time. Reflection is not possible in other programming languages such as c++.

Here i wrote a simple java program to know how reflection works.

StudentModel.java


/**
* JavaBelazy Java source code download
*/

/**
* @author +belazy
*
*/
public class StudentModel {

private String name = "javasourcecode";

private int id = 622;

private boolean isPassed = false;

//private double totalMark = 788;



public String getName() {
return name;
}

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

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public boolean isPassed() {
return isPassed;
}

public void setPassed(boolean isPassed) {
this.isPassed = isPassed;
}





}




Facebook comments