Posts which you will also like.

Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Friday, March 15, 2013

How to read / write excel files in java ?


In this blog post We will learn how to create/read excel files in java.
For all type of Microsoft Documents we can use an open source lib – Apache POI.
This library can help us to read/writer all Microsoft Document Formats,But we will use it for excels only.
Apache POI provides two type of API for excel manipulation
  • POI-HSSF – excel manipulation in excel –97(2007) file format(xls)
  • POI-XSSF - excel manipulation in excel –2007 file format(xlsx)
Steps to follow to create an excel file:
  • Create a new workbook:  Work book creates the excel files which we can use for read and write.Work Book can be created in two way-
    Workbook wb = new HSSFWorkbook();// For old format

    or

    Workbook wb = new XSSFWorkbook();// For new format

  • Create the sheets inside the workbook: These sheets contains cells in which the actual data resides.

    Sheet sheet1 = wb.createSheet("Result");
    Sheet sheet2 = wb.createSheet("Result2");
  • Create the rows inside sheet to hold the cells:  Row row = sheet.createRow((0);//Note that rows are zero index based i.e. first row starts with 0 index.


  • Create the cells inside the row to hold the data: Cells are also zero index based as rows.

    Cell cell = row.createCell(0);

    cell.setCellValue(1);

  • Writing the excel sheet to a file:

     FileOutputStream fileOut = new FileOutputStream("my_workbook.xlsx");
     wb.write(fileOut);
     fileOut.close();

Steps to follow to read an excel file:        InputStream input = new FileInputStream("my_workbook.xlsx");
    Workbook wBook = WorkbookFactory.create(input);
    Sheet sheet = wBook.getSheetAt(0);
    Row row = sheet.getRow(2);
    Cell cell = row.getCell(3);


Example:


public class ExcelWriter {
    public static void main(String[] args) {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("demo sheet");

        // Create a row and put some cells in it. Rows are 0 based.
        Row row = sheet.createRow((short)0);
        // Create a cell and put a value in it.
        row.createCell(1).setCellValue(999);
        row.createCell(2).setCellValue("Empty Heart");
        row.createCell(3).setCellValue(true);

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream("demo.xls");
        wb.write(fileOut);
        fileOut.close();
    }
}
Read More ->>

Monday, January 14, 2013

Using Regular Expressions in Java



In this java tutorial we will learn to use regular expression in java.Regular expression is very powerful tool for text manipulation and searching.It provides the fastest searching in huge amount of available data.So if you know it definitely you will save a lot time while doing these operations.In this tutorial I am going to describe how to use regular expression in java,I will not teach you the regular expression(If you are new to regular expression then please update yourself first via techcresendo.com)
In java we have java.util.regex package for regular expressions.This package basically contains three classes
  • Pattern:  This class represents the pattern in regular expression.Pattern is basically a format of text which needs to be matched in a group of texts.Patterns are constructed using regular expressions. e.g pattern
  • "[tT]rue" matches true or True

  • Matcher:  This class does the matching of the compiled pattern against an input string.

  • PatternSyntaxException: This class represents the exception which are thrown when your regular expression pattern is not correct.(It is unchecked exception)
Steps to create a pattern matching program:
  1. Create a pattern object.This object defines your regular expression.                                                                                                                           Pattern pattern=Pattern.compile(“regex”);

  2. Now with the help of Pattern object we can get Matcher object for a given input text(into which pattern to be  matched).                                                                                                                                                       Matcher matcher=pattern.matcher(INPUT_TEXT); 

  3. Now using this matcher object  we can easily find the pattern in the text as we will see in the example program.

package com.techy.rajeev;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatch {
  public static final String INPUT_TEXT = "This is a test for regular expression Testing.";
  public static final String PATTERN = "[tT]est";
  
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile(PATTERN);
    Matcher matcher = pattern.matcher(INPUT_TEXT);
    while (matcher.find()) {
      System.out.print("Start pos: " + matcher.start());
      System.out.print(" End pos: " + matcher.end() + " ");
      System.out.println(matcher.group());
    }
  }
} 



Output:

Start pos: 10 End pos: 14 test
Start pos: 38 End pos: 42 Test
Read More ->>

Tuesday, December 25, 2012

How to create SFTP connection using java ?



In this blog post we will learn how to create a secure FTP connection using java.SFTP is much more secure than its predecessor FTP since SFTP is based on SSH.
Here We will develop a SFTP client.Basically SFTP clients are programs that use SSH to access, manage, and transfer files. SFTP clients are functionally similar to FTP clients, but they use different protocols.
To create a SFTP connection to a server for file transfer or any other FTP operation we will use an open source library called JSCh. You can download this library from http://www.jcraft.com/
Add this library to your class path and start creating the program.
This example shows how to get a file from the server using SFTP.
package com.techy.rajeev;

import com.jcraft.jsch.*;

    /**
     * @param args
     */

    public class SFTPTest {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        String username="";//Put your username here
        String password="";//Put your password here
        String host="";//Hostname
        String sourceFile="";//Path of file on the server
        String destFile="";//Path of local file
        try {
            session = jsch.getSession(username,host,22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;

            sftpChannel.get(sourceFile,destFile);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace(); 
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
Read More ->>

Monday, December 17, 2012

Java program to generate all possible sub string of a string


This simple java program generates all possible sub string of given string.You can replace string with StringBuilder or StringBuffer where performance is issue.
package com.techy.rajeev;

public class GenStr {

    /**
     * @param args
     */
    public static void genAllSubStr(String str){
        for(int i=0;i<str.length();i++){
            for(int j=i;j<str.length();j++){
                System.out.println(str.substring(i, j+1));
            }
        }
    }
    public static void main(String[] args) {
        genAllSubStr("abc");
    }

}


Output:

a
ab
abc
b
bc
c

Read More ->>

Tuesday, December 4, 2012

Java program to generate permutation of a string


This post is about generating permutation of a string using a java program.This program has a static method  genPerm() method which is used for generation of permutation of the string. genPerm() method is recursive and takes two string arguments and prints the permutations of the second string.
Source Code:
public class GeneratePerm {

    /**
     * @param args
     */
    public static void genPerm(String pString,String sb){
        if(pString.length()==3)
            System.out.println(pString);
        for(int i=0;i<sb.length();i++){
            genPerm(pString+sb.charAt(i),sb.replaceFirst(sb.charAt(i)+"",""));
        }
    }
    public static void main(String[] args) {
        String sb=new String("abc");
        genPerm("",sb);
    }

}

Output:
abc
acb
bac
bca
cab
cba

Read More ->>

Saturday, September 22, 2012

Java Tutorial on GridBagLayout Manager


In this java tutorial we are going to discuss about GridBagLayout Manager.
GridBagLayout manager is one of the most powerful but complex layout manager in java.It is somewhat similar to GridLayout in the sense that it also arranged the components in the grid, but here component added can be of varying sizes i.e we can increase or decrease their size to occupy more than one row or column of the grid.
If suppose you are going to use this layout manager in your program then you first decide and draw the outline of GUI you need then proceed further.Life will be much easier(Really).
Most important parts of the GridBagLayout are GridBagConstraints .They specify the size and position, and many more constraints  of the each component. We will discuss about each GridBagConstraints fields.

gridx The column in which the component will be placed
gridy The row in which the component will be placed.
gridwidth The no of column the component occupies.
gridheight The no of rows the component occupies.
weightx The amount of extra space to allocate horizontally. The grid
slot can become wider when extra space is available.
weighty The amount of extra space to allocate vertically. The grid slot
can become taller when extra space is available.
anchor When component added is smaller than its area then we can use anchor to specify its position.Possible positions are NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST,
NORTHWEST or CENTER
fill This basically tell how to resize the component when container area is bigger than it’s size.
We can have a single “GridBagConstraints” instance which is used for specifying the constraints of all the components or seperate “GridBagConstraints” for each of them.
But it is recommended to use seperate “GridBagConstraints” for each of the component added to the container using GridBagLayout Manager.
Now we will use the GridBagLayout in our sample program:


package com.techy.rajeev;

import java.awt.EventQueue;

public class GridBagLayoutTest {

    private JFrame frmTechyrajeev;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GridBagLayoutTest window = new GridBagLayoutTest();
                    window.frmTechyrajeev.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public GridBagLayoutTest() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmTechyrajeev = new JFrame();
        frmTechyrajeev.setTitle("techyrajeev");
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0};
        gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
        gridBagLayout.columnWeights = new double[]{1.0, 0.0, 1.0, 1.0, 0.0,
 Double.MIN_VALUE};
        gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
 Double.MIN_VALUE};
        frmTechyrajeev.getContentPane().setLayout(gridBagLayout);
        
        JLabel lblLoginForm = new JLabel("Login Form");
        GridBagConstraints gbc_lblLoginForm = new GridBagConstraints();
        gbc_lblLoginForm.insets = new Insets(5, 0, 5, 5);
        gbc_lblLoginForm.gridx = 2;
        gbc_lblLoginForm.gridy = 0;
        frmTechyrajeev.getContentPane().add(lblLoginForm, gbc_lblLoginForm);
        
        JLabel lblEnterUsername = new JLabel("Username:");
        GridBagConstraints gbc_lblEnterUsername = new GridBagConstraints();
        gbc_lblEnterUsername.anchor = GridBagConstraints.EAST;
        gbc_lblEnterUsername.insets = new Insets(0, 0, 5, 5);
        gbc_lblEnterUsername.gridx = 1;
        gbc_lblEnterUsername.gridy = 1;
        frmTechyrajeev.getContentPane().add(lblEnterUsername, gbc_lblEnterUsername);
        
        textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 5);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 2;
        gbc_textField.gridy = 1;
        frmTechyrajeev.getContentPane().add(textField, gbc_textField);
        textField.setColumns(10);
        
        JLabel label = new JLabel("");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 1;
        gbc_label.gridy = 2;
        frmTechyrajeev.getContentPane().add(label, gbc_label);
        
        JLabel lblPassword = new JLabel("Password:");
        GridBagConstraints gbc_lblPassword = new GridBagConstraints();
        gbc_lblPassword.anchor = GridBagConstraints.EAST;
        gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
        gbc_lblPassword.gridx = 1;
        gbc_lblPassword.gridy = 3;
        frmTechyrajeev.getContentPane().add(lblPassword, gbc_lblPassword);
        
        textField_1 = new JTextField();
        GridBagConstraints gbc_textField_1 = new GridBagConstraints();
        gbc_textField_1.insets = new Insets(0, 0, 5, 5);
        gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_1.gridx = 2;
        gbc_textField_1.gridy = 3;
        frmTechyrajeev.getContentPane().add(textField_1, gbc_textField_1);
        textField_1.setColumns(10);
        
        JButton btnLogin = new JButton("Login");
        GridBagConstraints gbc_btnLogin = new GridBagConstraints();
        gbc_btnLogin.insets = new Insets(0, 0, 5, 5);
        gbc_btnLogin.gridx = 2;
        gbc_btnLogin.gridy = 4;
        frmTechyrajeev.getContentPane().add(btnLogin, gbc_btnLogin);
        
        JTextArea txtrThisIsA = new JTextArea();
        txtrThisIsA.setText("This is a text area.");
        GridBagConstraints gbc_txtrThisIsA = new GridBagConstraints();
        gbc_txtrThisIsA.gridwidth = 5;
        gbc_txtrThisIsA.fill = GridBagConstraints.BOTH;
        gbc_txtrThisIsA.gridx = 0;
        gbc_txtrThisIsA.gridy = 6;
        frmTechyrajeev.getContentPane().add(txtrThisIsA, gbc_txtrThisIsA);
    }

}


GridBagLayout2


This is the grid view of rows and columns of the frame.As you can see it is very easy to divide the whole Gui into rows and columns on the paper and then proceed accordingly for the actual designing using GridBagLayout Manager.


Output of this GridBagLayout tutorial program is:


gridBagLayout
Read More ->>

Thursday, September 13, 2012

Java Tutorial on Anonymous Inner Class


An anonymous inner class is a very strange type of inner class.It can be created on the fly when needed and It can also be defined inside method argument!.
We will cover all the details about anonymous inner class in this blog post so continue reading.
As the name suggests anonymous inner classes do not have any name so how would you recognize a inner class? Anonymous inner classes are recognized by their parent’s type.Here parent could be either a class or interface.Basically anonymous inner class can be categorized into two types:
  • As a class providing implementation to a predefined interface.
  • As a class providing implementation to a predefined class or a abstract class
Now we will see both methods
Pointing up
class Test{
            public void doTesting(){
              System.out.println("Testing is on the way!");
             }
            }
public class InnerJ{
    Test t=new Test(){
            public void doTesting(){
                System.out.println("Testing completed!");
            }
        };//watch out for semicolon
}



Here what we are saying basically  is,that create a anonymous class(without any name) which is a subclass of type Test(extends Test) and declare a reference variable of type Test to hold that anonymous class object since at the same time we are instantiating that anonymous inner class(see the new key word in InnerJ).


Fingers crossed



//Now same thing with interface 
interface Test{ 
            void doTesting(); 
            } 
public class InnerJ{

//Beware this not instantiation of interface ! 
    Test t=new Test(){ 
            public void doTesting(){ 
                System.out.println("Testing completed!"); 
            } 
        };//watch out for semicolon 
}


here instead of saying extends we say implements and every thing is same.


Restrictions on anonymous inner class:



  • Anonymous inner classes can implement only one interface


  • Anonymous inner classes can either extends a class or implement an interface at a time

Read More ->>

Thursday, August 30, 2012

Java program to divide an image into multiple equal parts



In this post I am going to demonstrate how to divide an image into equal parts.Here I have used simple Java image api to manipulate the source image via techcresendo.com
In this java program for image dividing ,I have first divided the image into smaller equal size parts and placed them randomly on the buttons on the frame using Grid Layout .
Input Image:
img

This program can be used further to develop sliding game puzzle in java.
package com.techy.rajeev.divideImage;

import java.awt.EventQueue;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class MainWin {

    private JFrame frame;
    private JButton []jb=new JButton[9];
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWin window = new MainWin();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MainWin() {
        try {
            initialize();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(100, 100, 612, 519);
        setImage();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(3, 3));
        for(int i=0;i<9;i++){
            frame.add(jb[i]);
        }
    }

    public void setImage() throws IOException{
        URL img=MainWin.class.getResource("/img/img.jpg");
        BufferedImage bimg=ImageIO.read(img);
        int w=bimg.getWidth();
        int h=bimg.getHeight();
        int count=0;
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                BufferedImage wim=bimg.getSubimage(i*w/3,j*h/3, w/3, h/3);
                Image sc=wim.getScaledInstance(frame.getWidth()/3,


               frame.getHeight()/3, Image.SCALE_AREA_AVERAGING);
                setupImage(count++,sc);
            }
        }
    }

    private void setupImage(int i,Image wim) {
        jb[i]=new JButton(new ImageIcon(wim));
    }

}


Output:


imgdivide

Read More ->>

Tuesday, August 28, 2012

Extracting text from images




In this blog post we are going to discuss about the tools and api for extracting the text from the image.Some of these tools and apis are free and open source but some of them are not free but still you can send request to the company to get developer’s version for free.
Java OCR:
Java OCR is a simple and efficient java based open source library for image processing and optical character recognition.This library can also be used in the development of android based project.
265598
If you want to test it just click here to download it and give it a try.
Tesseract-OCR:
This is the one of the best optical character recognition open source library available .It was originally developed by HP Labs but now supported by Google.It is the one of the most accurate OCR engine. It can read wide variety of image formats and text read can be converted into different languages also.As of now It supports more than 40 languages and new languages are being implemented.
It is developed in c++ and if you are a java developer then don’t worry you may  be able find some JNI wrapper for it.
Tess4j is one of the available java JNI wrapper of tesseract-OCR.
There are some graphical front end already available.If you want  to check the functionality of Tesseract-OCR you can download gImageReader,VietOCR .Other than them there are many more GUI front end are available on the web.
blg
Asprise OCR for Java:  
Asprise Lab provides Asprise OCR SDK for development of OCR in java.It also provides the web based solution for optical character recongition.It enables us to equip our Java applications (Java applets, web applications, standard applications, J2EE enterprise applications) with optical character recognition (OCR) ability.
bc
But this SDK is not free, for commercial usage you need to buy the License.
Via - techcresendo.com
Read More ->>

Friday, August 3, 2012

Passing Command Line Argument in Eclipse


Passing command line arguments in Eclipse is very easy.We will see step by step procedure to pass command line arguments to a java program using eclipse.

package com.techy.rajeev;

class BadFoodException extends Exception {

}
class Myexception{
    public static void checkfood(String food)throws BadFoodException{
        if(food.equals("Veg")){
            System.out.println("Good food :)");
        }else{
            throw new BadFoodException();
        }
    }
    public static void main(String args[]){
        for(String s: args){
            try {
                checkfood(s);
            } catch (BadFoodException e) {
                e.printStackTrace();
            }
        }
        System.out.println("survived");
    }
}


This is the java program for which we want to pass command line arguments.

Write this program in eclipse IDE and save it.

Now click on the small dropdown icon beside run icon as shown in image:

eclipse1

A drop down menu will appear.Now click on Run Configurations.


eclipse


Now a new window will appear.This window provide us the settings for the run time configurations of a program.


In this window click on the arguments tab and supply the arguments needed by your program separated via space as delimiter.


eclipse3

Thats it.

More on this at techcresendo.com
Read More ->>

Wednesday, July 25, 2012

Java Tutorial:Difference Between equals and ==


Sometimes in our java code we find that equality comparison operators(equals() and ==) do not work as expected.But why is that happening so? We know how they works Smile.

Really?

Actually we don’t know in depth how they work.So in this java tutorial I am going to show how equals and == works and what is difference between them.So keep reading this java tutorial.

equals():

This method compares the actual content inside the object i.e two instances of a class having content with same meaning  e.g

Integer num1=new Integer(10);

Integer num2=new Integer(10);

so num1.equals(num2) is true as obvious.

==:

== compares the references i.e the reference which is referring to the actual object not the content inside the object.Then if two references referring to the same object then references will be same. e.g

Integer num1=new Integer(1000);

Integer num2=num1; Now num2 is also referring to 1000

so num1==num2 is true.

Suppose if we say Integer num2=new Integer(1000); Now a new Integer object is created on the heap and its reference is assigned to num2.

so num1==num2 is false.

Now guess the output of

Integer n1=10; Integer n2=10;

if(n1==n2)

System.out.println(“same object”);

else

System.out.println(“Diff.object”);

Output is: same object

Yes that’s true;behaviour of == changes when boxing involves.This strange behaviour happens because JVM create the literal pool same as (String constant pool) for following wrapper objects (which must have been created through boxing)

  • Boolean
  • Byte
  • Character range(\u0000 to \u007f)
  • Short
  • Integer range(-128 to 127)

So whenever you are creating such wrapper object then first it will be searched in it’s respective constant pool if it is found there it’s reference will be returned to new reference of wrapper object other wise it is created and stored in the pool.This strange thing happens just to save memory.

Read More ->>

Saturday, June 23, 2012

Java Multiple Choice Questions(MCQ)


This post contains 20 multiple choice question (mcq) in java.Try to solve them for your practice......

1.Given: public class Mule { public static void main(String[] args) { boolean assert = true; if(assert) { System.out.println("assert is true"); } } } Which command-line invocations will compile? 
a.javac Mule.java
b.javac -source 1.3 Mule.java
c.javac -source 1.4 Mule.java
d.javac -source 1.5 Mule.java
2) Which exception is thrown by read() method of InputStream class
a.Exception
b.FileNotFoundException
c.IOException
d.None
3)Given: String test = "a1b2c3"; String[] tokens = test.split("\\d"); for(String s: tokens) System.out.print(s + " "); What is the result?
a.a b c
b.1 2 3
c.a1b2c3
d.a1 b2 c3
4)Given: public class Person { private name; public Person(String name) { this.name = name; } public int hashCode() { return 420; } } Which statement is true?
a.The time to find the value from HashMap with a Person key depends on the size of the map.
b.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
c.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
d.The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.
5)Given: abstract class C1 { public C1() { System.out.print(1); } } class C2 extends C1 { public C2() { System.out.print(2); } } class C3 extends C2 { public C3() { System.out.println(3); } } public class Ctest { public static void main(String[] a) { new C3(); } } What is the result?
a.3
b.23
c.32
d.123
6)Given: class One { public One foo() { return this; } } class Two extends One { public One foo() { return this; } } class Three extends Two { // insert method here } Which methods, inserted individually, correctly complete the Three class?
a.public void foo() {}
b.public int foo() { return 3; }
c.public Two foo() { return this; }
d.public Object foo() { return this; }
7)Which statements is true?
a.A final method in class X can be abstract if and only if X is abstract.
b.A protected method in class X can be overridden by any subclass of X.
c.A private static method can be called only within other static methods in class X.
d.A non-static public final method in class X can be overridden in any subclass of X.
8)Given: public interface Status { /* insert code here */ int MY_VALUE = 10; } Which three are valid on line
a.final
b.native
c.private
d.abstract
9)A team of programmers is involved in reviewing a proposed design for a new utility class. After some discussion, they realize that the current design allows other classes to access methods in the utility class that should be accessible only to methods within the utility class itself. What design issue has the team discovered?
a.Weak encapsulation
b.Strong encapsulation
c.High cohesion
d.Tight coupling
10)Which of the following strings can be used as mode strings for creating a RandomAccessFile object? 
a.“r”
b.“w”
c.“wr”
d.“0”
11)Given: public class TestOne { public static void main (String[] args) throws Exception { Thread.sleep(3000); System.out.println("sleep"); } } What is the result?
a.Compilation fails.
b.An exception is thrown at runtime.
c.The code executes normally and prints "sleep".
d.The code executes normally, but nothing is printed.
12)Given: class Mammal { } class Raccoon extends Mammal { Mammal m = new Mammal(); } class BabyRaccoon extends Mammal { } Which four statements are true?
a.Raccoon is-a Mammal.
b.BabyRaccoon has-a Mammal.
c.BabyRaccoon is-a Raccoon.
d.BabyRaccoon is-a BabyRaccoon.
13)Which of the following lines will not compile? byte b1=5, b2=3, b3; Short s=25; b2=s; b3=b1*b2;
a.Line 1only
b.Line 3 only
c.Line 4 only
d.Line 1 and 4 only
14)Given: class Nav{ public enum Direction { NORTH, SOUTH, EAST, WEST } } public class Sprite{ // insert code here } Which code,at "inserted code here", allows the Sprite class to compile?
a.Direction d = NORTH;
b.Nav.Direction d = NORTH;
c.Direction d = Direction.NORTH;
d.Nav.Direction d = Nav.Direction.NORTH;
15)Given: public static void main(String[] args) { Object obj = new int[] { 1, 2, 3 }; int[] someArray = (int[])obj; for (int i : someArray) System.out.print(i + " "); } What is the result?
a.1 2 3
b.Compilation fails because of an error
c.A ClassCastException is thrown at runtime.
d.none
16)Given: import java.util.*; public class SortOf { public static void main(String[] args) { public static void main(String[] args) { a.add(1); a.add(5); a.add(3); Collections.sort(a); a.add(2); Collections.reverse(a); System.out.println(a); } } What is the result?
a.[1, 2, 3, 5]
b.[2, 1, 3, 5]
c.[2, 5, 3, 1]
d.[5, 3, 2, 1]
17)Which two scenarios are NOT safe to replace a StringBuffer object with a StringBuilder object?
a.When using versions of Java technology earlier than 5.0.
b.When sharing a StringBuffer among multiple threads.
c.When using the java.io class StringBufferInputStream.
d.When you plan to reuse the StringBuffer to build more than one string.
18)Which of the following statements are true?
a.Unicode characters are all 16 bits
b.UTF characters are all 24 bits
c.Reader class is byte stream class
d.None
19)Which statements are reserved words in Java?
a.run
b.imports
c.default
d.implement
20)DataInputStream is
a.An abstract class defined in java.io
b.A class we can use to read primitive data type
c.An interface that defines methods to open files
d.An interface that defines methods to read primitive data types


For more such mcq please visit our partner techcresendo.com
Read More ->>

Thursday, April 19, 2012

How to create 3D Games in Java?


For creating 3D games in java you need to work with various kinds of java 3d libraries such as Java 3D APIs and Jogl libraries etc.It will be very cumbersome if you want to develop professional quality games since you will have to manage Graphics,Animations,Sprites,Game physics etc etc by yourself.
But your task will be greatly simplified if you have some game engine and 3d game maker program like Unreal Development Kit or Unity 3D.These two game engines are equipped with really great features and have been used in creating professional games.But one major disappointment for a java programmer is that they do not support java as programming language.
But there is one solution for this problem: JMONKEYENGINE 3.0
jMonkeyEngine is a SDK based on NetBeans Programming Platform and bundled with complete solutions for a 3d game making.If you worked with NetBeans already they it would much more easier to build any project in JMonkeyPlatform.
jmonkey
JMonkeyPlatform also support some other language such as such as XML, PHP, Groovy, Ruby, Scala, and even C/C++ to create 3d games so if you are efficient at these they you can use them too.One more important point is that JMonkeyEngine is open source project and is licensed under the New BSD license.
JMonkeyEngine supports following features needed by any game developer to create a 3d game


  • Shaders
  • Lighting
  • Physics
  • Special Effects
  • Asset System
  • Supported Formats
  • Texturing
  • Terrain
  • Graphical User Interface
  • Networking
  • Miscellaneous

                                                  Download JMonkeyEngine SDK

Read More ->>

Friday, March 30, 2012

Java Tutorial on Circular Doubly Linked List with Generics


Circular Doubly Linked List is very much similar to Doubly Linked List with few differences such as there is no end of the list i.e Head node points to Tail node and Tail node also points to Head node.So if you do not properly check the termination condition then you will probably find yourself in an infinite loop.
Circular Doubly Linked List is advanced version of Circular Linked List.
Circular Doubly Linked List
DLNode class is similar to previous one used Generic Doubly Linked List.
Complete Java code related to Circular Doubly Linked List is listed below.
Pointing upDLNode.java:
package com.techy.rajeev;

public class DLNode<T> {
    private T data;
    private DLNode<T> next;
    private DLNode<T> prev;
    DLNode(){
        next=null;
        prev=null;
        data=null;
    }
    DLNode(T data) {
        this(data, null, null);
    }
    DLNode(T data, DLNode<T> next, DLNode<T> prev) {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }

    T getData() {
        return data;
    }
    public void setNextNode(DLNode<T> next) {
        this.next = next;
    }
    public DLNode<T> getPrevNode() {
        return prev;
    }
    public void setPrevNode(DLNode<T> prev) {
        this.prev = prev;
    }
    public void setData(T data) {
        this.data = data;
    }
    public DLNode<T> getNextNode() {
        return next;
    }
}



Pointing upCircularDoublyLinkedList.java:





package com.techy.rajeev;

public class CircularDoublyLinkedList<T> {
    private DLNode<T> head;

    // Returns the no. of nodes in circular Doubly linked list
    public int getSize() {
        int count = 0;
        if (head == null)
            return count;
        else {
            DLNode<T> temp = head;
            do {
                temp = temp.getNextNode();
                count++;
            } while (temp != head);
        }
        return count;
    }

    // Traversal of circular doubly linked list
    public void traverse() {
        if (head == null) {
            System.out.println("List is empty!");
        } else {
            DLNode<T> temp = head;
            do {
                System.out.print(temp.getData() + " ");
                temp = temp.getNextNode();
            } while (temp != head);
        }

    }

    /* methods related to insertion in circular doubly linked list starts. */
    public void insertAtBeg(T data) {
        DLNode<T> newnode = new DLNode<T>(data);
        if (head == null) {
            newnode.setNextNode(newnode);
            newnode.setPrevNode(newnode);
            head = newnode;
        } else {
            DLNode<T> temp = head.getPrevNode();
            temp.setNextNode(newnode);
            newnode.setPrevNode(temp);
            newnode.setNextNode(head);
            head.setPrevNode(newnode);
            head = newnode;
        }

    }

    public void insertAtEnd(T data) {
        DLNode<T> newnode = new DLNode<T>(data);
        if (head == null) {
            newnode.setNextNode(newnode);
            newnode.setPrevNode(newnode);
            head = newnode;
        } else {
            DLNode<T> temp = head.getPrevNode();
            temp.setNextNode(newnode);
            newnode.setNextNode(head);
            head.setPrevNode(newnode);
            newnode.setPrevNode(temp);
        }

    }

    public void insertAtPosition(T data, int position) {
        if(position<0||position==0){
            insertAtBeg(data);
        }    
    else if(position>getSize()||position==getSize()){
            insertAtEnd(data);
        }else{
            
            DLNode<T>temp=head;
            DLNode<T> newnode=new DLNode<T>(data);
            for(int i=0;i<position;i++){
                temp=temp.getNextNode();
            }
            
            newnode.setNextNode(temp.getNextNode());
            temp.getNextNode().setPrevNode(newnode);
            temp.setNextNode(newnode);
            newnode.setPrevNode(temp);
        }
    }

    /* methods related to insertion in circular doubly linked list ends. */

    /* methods related to deletion in circular doubly linked list starts. */
    // Removal based on a given node for internal use only
    @SuppressWarnings("unused")
    private void remove(DLNode<T> node) {
        if(node.getPrevNode()==node||node.getNextNode()==node)
            head=null;
        else{
            DLNode<T> temp=node.getPrevNode();
            temp.setNextNode(node.getNextNode());
            node.getNextNode().setPrevNode(temp);
            }
        node=null;
    }
    public void removeAtBeg(){
        if(head==null)
            System.out.println("List is already empty!");
        else{
            DLNode<T> temp=head.getNextNode();
            head.getPrevNode().setNextNode(temp);
            temp.setPrevNode(head.getPrevNode());
            head=temp;
        }
    }
    public void removeAtEnd(){
        if(head==null)
            System.out.println("List is already empty!");
        else{
            DLNode<T> temp=head.getPrevNode();
            temp.getPrevNode().setNextNode(head);
            head.setPrevNode(temp.getPrevNode());
            temp=null;
        }
    }
    // Removal based on a given position
    public T remove(int position) {
        T data = null;
        if (position == 0) {
            data = head.getData();
            removeAtBeg();
        } else if (position == getSize()-1) {
            data=head.getPrevNode().getData();
            removeAtEnd();
        } else {
            DLNode<T> temp = head;
            for (int i = 0; i < position; i++) {
                temp = temp.getNextNode();
            }
            data=temp.getData();
            DLNode<T> node = temp.getNextNode();
            node.setPrevNode(temp.getPrevNode());
            temp.getPrevNode().setNextNode(node);
            temp = null;
        }
        return data;// Deleted node's data
    }
    /* methods related to deletion in circular doubly linked list ends. */

}


Pointing upMainClass.java




package com.techy.rajeev;
//Circular Doubly Linked list is used here.
public class MainClass {
    public static void main(String args[]){
        CircularDoublyLinkedList< Integer> cdll=new CircularDoublyLinkedList<Integer>();
        cdll.insertAtBeg(32);
        cdll.insertAtBeg(35);
        cdll.insertAtBeg(45);
        cdll.insertAtEnd(12);
        cdll.insertAtEnd(10);
        cdll.insertAtEnd(9);
        cdll.traverse();
        System.out.println();
        System.out.println("Size is:"+cdll.getSize());
        cdll.insertAtPosition(11,5);//Index starts from zero.
        System.out.println();
        cdll.traverse();
        System.out.println("\nSize is:"+cdll.getSize());
        System.out.println();
        System.out.println("Deleted:"+cdll.remove(5));
        //Index for deletion also starts from zero
        cdll.removeAtBeg();
        cdll.traverse();
        cdll.removeAtEnd();
        System.out.println();
        cdll.traverse();
        System.out.println("Size is:"+cdll.getSize());
    }
}


Pointing upOUTPUT:


45 35 32 12 10 9 11

Size is:7


Deleted:9

35 32 12 10 11


35 32 12 10 Size is:4

More on this at techcresendo.com
Read More ->>

Sunday, March 25, 2012

Java Tutorial on Generic Doubly Linked List


In this Java tutorial We discuss Doubly Linked List.Doubly linked list is a two way linked list where each node in the list has two links.
doublylinkedlist_03
With the help of double links we can traverse the list in both forward and backward direction in O(n) time.
If We maintain two pointers for head and tail then insertion and deletion at beginning and end can be done in O(1) time.

Sad smileBut doubly linked list has some disadvantage also e.g.
1.It requires much memory since we have to maintain two reference for each node: one for forward node and one for backward node.
2.Insertion and deletion requires much more effort since we have to change four reference for each insertion and deletion except at beginning and at end.
doublylinkedlist from techyrajeev
techyrajeev doublylinkedlist image
We can implement the Generic Doubly Linked list using java.Complete java code listing is given below.


Pointing upDLNode.java: This java file represents the node which has double links next and prev.



package com.techy.rajeev;

public class DLNode<T> {
    private T data;
    private DLNode<T> next;
    private DLNode<T> prev;
    DLNode(){
        next=null;
        prev=null;
        data=null;
    }
    DLNode(T data) {
        this(data, null, null);
    }
    DLNode(T data, DLNode<T> next, DLNode<T> prev) {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }

    T getData() {
        return data;
    }
    public void setNextNode(DLNode<T> next) {
        this.next = next;
    }
    public DLNode<T> getPrevNode() {
        return prev;
    }
    public void setPrevNode(DLNode<T> prev) {
        this.prev = prev;
    }
    public void setData(T data) {
        this.data = data;
    }
    public DLNode<T> getNextNode() {
        return next;
    }
}



Pointing upDoublyLinkedList.java:




package com.techy.rajeev;

public class DoublyLinkedList<T> {
    private DLNode<T> head;
    private DLNode<T> tail;
    //Returns the no. of nodes in Doubly linked list
    public int getSize(){
        int count = 0;
        if(head==null)
            return count;
        else{
            DLNode<T> temp=head;
            do{
                temp=temp.getNextNode();
                count++;
            }while(temp!=tail);
        }
        return count;
    }
    //Traverse from head
    public void traverseF(){
        DLNode<T> temp=head;
        while(temp!=null){
            System.out.print(temp.getData()+" ");
            temp=temp.getNextNode();
        }
    }
    //Traverse from tail
    public void traverseB(){
        DLNode<T> temp=tail;
        while(temp!=null){
            System.out.print(temp.getData()+" ");
            temp=temp.getPrevNode();
        }
    }
    /* methods related to insertion in doubly linked list starts.*/
    public void insertAtBeg(T data){
        DLNode<T> newnode=new DLNode<T>(data);
        if(head==null){
            head=newnode;
            tail=newnode;
            newnode.setNextNode(null);
            newnode.setPrevNode(null);
        }else{
             newnode.setNextNode(head);
             head.setPrevNode(newnode);
             head=newnode;
        }
            
    }
    public void insertAtEnd(T data){
        DLNode<T> newnode=new DLNode<T>(data);
        if(tail==null){
            head=newnode;
            tail=newnode;
            newnode.setNextNode(null);
            newnode.setPrevNode(null);
        }else{
            newnode.setPrevNode(tail);
            tail.setNextNode(newnode);
            tail=newnode;
        }
    }
    public void insertAtPosition(T data,int position){
        if(position<0||position==0){
            insertAtBeg(data);
        }    
    else if(position>getSize()||position==getSize()){
            insertAtEnd(data);
        }else{
            
            DLNode<T>temp=head;
            DLNode<T> newnode=new DLNode<T>(data);
            for(int i=0;i<position-1;i++){
                temp=temp.getNextNode();
            }
            
            newnode.setNextNode(temp.getNextNode());
            temp.getNextNode().setPrevNode(newnode);
            temp.setNextNode(newnode);
            newnode.setPrevNode(temp);
        }
    }
    /* methods related to insertion in doubly linked list ends.*/
    
    /* methods related to deletion in doubly linked list starts.*/
    //Removal based on a given node for internal use only
    @SuppressWarnings("unused")
    private void remove(DLNode<T> node){
        if(node.getPrevNode()==null)
            head=node.getNextNode();
        else if(node.getNextNode()==null)
            tail=node.getPrevNode();
        else{
            DLNode<T> temp=node.getPrevNode();
            temp.setNextNode(node.getNextNode());

          node.getNextNode().setPrevNode(temp);

           }
        node=null
    }
    //Removal based on a given position
    public T remove(int position){
        T data=null;
        if(position==1){
            data=head.getData();
            head=head.getNextNode();
        }else if(position==getSize()){
            data=tail.getData();
            tail=tail.getPrevNode();
            tail.setNextNode(null);
        }else{
            DLNode<T> temp=head;
            for(int i=0;i<position;i++){
                temp=temp.getNextNode();
            }
            DLNode<T> node=temp.getNextNode();
            node.setPrevNode(temp.getPrevNode());
            temp.getPrevNode().setNextNode(node);
            temp=null;
        }
        return data;//Deleted node's data
    }
    /* methods related to deletion in doubly linked list ends.*/
    
}

High fiveMainClass.java:

This is the class in which you can see the actual working of DoublyLinked List.



package com.techy.rajeev;

public class MainClass {
    public static void main(String args[]){
        DoublyLinkedList< Integer> dll=new DoublyLinkedList<Integer>();
        dll.insertAtBeg(32);
        dll.insertAtBeg(35);
        dll.insertAtBeg(45);
        dll.insertAtEnd(12);
        dll.traverseF();
        System.out.println();
        dll.traverseB();
        System.out.println("Size is:"+dll.getSize());
        dll.insertAtPosition(46,0);
        System.out.println();
        dll.traverseF();
        System.out.println("Removed at pos 5:"+dll.remove(5));
        System.out.println("Size is:"+dll.getSize());
        dll.traverseF();
        dll.remove(1);
        System.out.println();
        dll.traverseF();
        
    }
}

Clockoutput:

45 35 32 12
12 32 35 45 Size is:4

46 45 35 32 12 Removed at pos 5:12
Size is:4
46 45 35 32
45 35 32
Read More ->>

Tuesday, February 7, 2012

A Tutorial on Java for Solution Of Producer-Consumer Problem


Consumer Producer is a problem related to sharing of data.In this problem producer and consumers operates simultaneously on the shared data.More than one producers produce and more than one consumers consume.So two prevent resource quench we must use thread safety rules and enforce sequential access rather than concurrent access.
DIAGRAM-producer
To illustrate this situation we will use following code snippets :

Money Producer Class:

package com.techy.rajeev;

public class Producer implements Runnable {
    private SyncronizedStack stack;
    private int producerNum;
    public Producer(SyncronizedStack stack,int producerNum) {
        this.stack=stack;
        this.producerNum=producerNum;
    }

    public void run(){
        char c;
        for(int i=0;i<30;i++){
            c=(char)(Math.random()*26+'A');
            stack.push(c);
            System.out.println("Producer"+producerNum+"produced :"+c);
            try{
                Thread.sleep((int)(Math.random()*300));
                
            }catch(InterruptedException e){
                System.out.println("Error");
            }
        }
    }
}





Plate Consumer Class:


package com.techy.rajeev;

public class Consumer implements Runnable{
    private SyncronizedStack stack;
    private int consumerNum;
    public Consumer(SyncronizedStack stack,int consumerNum) {
        this.stack=stack;
        this.consumerNum=consumerNum;
    }

    public void run(){
        char c;
        for(int i=0;i<30;i++){
            c=stack.pop();
            System.out.println("Consumer"+consumerNum+"consumed:"+c);
            try{
                Thread.sleep((int)(Math.random()*300));
            }catch(InterruptedException e){
                System.out.println("Error");
            }
        }
    }

}


>Clock SynchronizedStack Class:

package com.techy.rajeev;

import java.util.Stack;

public class SyncronizedStack {
    private Stack<Character> buffer=new Stack<Character>();
    public synchronized char pop(){
        char c;
        while(buffer.size()==0){
            try{
                this.wait();
            }catch(InterruptedException e){
                
          }
        }
        c=buffer.remove(buffer.size()-1);
        return c;
    }
    public synchronized void push(char c){
        this.notify();
        buffer.add(c);
    }
}


Computer SyncTest Class:


package com.techy.rajeev;

public class SyncTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SyncronizedStack stack=new SyncronizedStack();
        Producer p1 =new Producer(stack,1);
        Thread t1=new Thread(p1);
        t1.start();
        Producer p2=new Producer(stack,2);
        Thread t2=new Thread(p2);
        t2.start();
        Consumer c1=new Consumer(stack,1);
        Thread ct1=new Thread(c1);
        ct1.start();
        Consumer c2=new Consumer(stack,2);
        Thread ct2=new Thread(c2);
        ct2.start();
    }

}

Thumbs up Output:

Producer1 produced :G
Consumer1 consumed:G
Consumer2 consumed:I
Producer2 produced :I
Producer1 produced :J
Consumer1 consumed:J
Producer2 produced :L
Consumer2 consumed:L
Producer1 produced :E
Consumer1 consumed:E
Consumer1 consumed:G
Producer2 produced :G
Producer1 produced :T
Consumer2 consumed:T
Producer2 produced :I
Consumer2 consumed:I
Producer1 produced :W
Consumer1 consumed:W
Producer2 produced :N
Consumer2 consumed:N
Producer1 produced :J
Consumer1 consumed:J
Producer1 produced :V
Consumer1 consumed:V
Producer2 produced :A
Consumer1 consumed:A
Producer1 produced :E
Consumer1 consumed:E
Producer2 produced :D
Consumer2 consumed:D
Producer2 produced :T
Consumer2 consumed:T
Producer2 produced :I
Consumer2 consumed:I
Producer2 produced :Z
Consumer1 consumed:Z
Producer1 produced :B
Consumer2 consumed:B
Consumer1 consumed:M
Producer2 produced :M
Producer1 produced :N
Consumer2 consumed:N
Consumer1 consumed:K
Producer2 produced :K
Producer1 produced :B
Consumer1 consumed:B
Consumer2 consumed:Y
Producer2 produced :Y
Consumer1 consumed:S
Producer2 produced :S
Consumer2 consumed:P
Producer2 produced :P
Producer1 produced :I
Producer2 produced :W
Producer2 produced :Z
Consumer1 consumed:Z
Producer2 produced :Y
Consumer2 consumed:Y
Producer1 produced :V
Producer1 produced :G
Consumer2 consumed:G
Consumer1 consumed:V
Consumer1 consumed:W
Producer2 produced :K
Consumer1 consumed:K
Consumer1 consumed:I
Producer1 produced :F
Consumer2 consumed:F
........
............
.......................
Read More ->>

Monday, February 6, 2012

A Tutorial on Java for Solution of The Josephus Problem


Light bulbDescription of the Problem: 
In this java tutorial we discuss about Josephus problem and its solution.
The Josephus Problem is a famous mathematical puzzle that goes back to ancient times. There are many stories to go with the puzzle. One is that Josephus was one of a group of Jews who were about to be captured by the Romans. Rather than be enslaved, they chose to commit suicide. They arranged themselves in a circle and, starting at a certain person, started counting off around the circle. Every nth person had to leave the circle and commit suicide.
Josephus decided he didn’t want to die, so he arranged the rules so he would be the last person left.
If there were (say) 20 people, and he was the seventh
person from the start of the circle, what number should he tell them to use for counting off?
The problem is made much more complicated because the circle
shrinks as the counting continues.
Thumbs up  Inputs are the number of people in the circle, the number used for counting off, and the number of the person where counting starts (usually 1). The output is the list of persons being eliminated.
Thumbs up When a person drops out of the circle, counting starts again from the person
who was on his left (assuming you go around clockwise).
Thumbs up Here’s an example.
There are seven people numbered 1 through 7, and you start at 1 and count off
by threes. People will be eliminated in the order 4, 1, 6, 5, 7, 3. Number 2 will remain at last
Solution of the Problem:
This problem can be solved by using a circular linked list. Complete listing of the java code is given below:
Pointing upCode for Circular linked list with some modified method(game())
package techy.rajeev;

public class CircularLinkedList {
    private Node start;
    private int count;
    public void append(int x){
        count++;
        Node temp=new Node(x);
        if(start==null){
            start=temp;
        }else{
            Node tp=start;
            while(tp.link!=start){
                tp=tp.link;
            }
            tp.link=temp;
        }
        temp.link=start;
    }
    public void addBeg(int x){
        count++;
        Node temp=new Node(x);
        if(start==null){
            temp.link=temp;
        }else{
            Node tp=start;
            while(tp.link!=start){
                tp=tp.link;
            }
            tp.link=temp;
            temp.link=start;
        }
        start=temp;
    }
    public void addAt(int pos,int x){
        Node temp,tp;
        temp=new Node(x);
        tp=start;
        for(int i=1;i<=pos;i++){
            if(tp.link==start)
                break;
            tp=tp.link;
        }
        temp.link=tp.link;
        tp.link=temp;
        count++;
    }
    public void displayList(){
        if(start==null)
            System.out.println("List is empty..");
        else{
        Node temp=start;
        System.out.print("->");
        while(temp.link!=start){
            System.out.println(" "+temp.data);
            temp=temp.link;
        }
        System.out.println(temp.data+" ->");
    }
}
    public void deleteAt(int position){
        Node current=start;
        Node previous=start;
        for(int i=0;i<position;i++){
            if(current.link==start)
                break;
            previous=current;
            current=current.link;
        }
        System.out.print(current.data);
        if(position==0)
            deleteFirst();
        else
            previous.link=current.link;
        count--;
    }
    public int deleteNode(Node node){
        Node current=start;
        Node previous=start;
        int data=node.data;
        while(current.data!=data){
            if(current.link==start)
                break; // Node does not exists in circular linked list
            previous=current;
            current=current.link;
        }
        previous.link=current.link;
        count--;
        return data;//returning the deleted data
    }
    public void deleteFirst() {
        Node temp=start;
        while(temp.link!=start){
            temp=temp.link;
        }
        temp.link=start.link;
        start=start.link;
        count--;
    }
    public int getCount(){
        return count;
    }
    /* Extra method for Josephus problem */
    public void game(int countToDeath,int persons){

        Node current=start;
        int caller=0;
        while(true){
            caller=current.data;
            System.out.print(caller+"Says->");
            for(int i=0;i<countToDeath;i++){
                current=current.link;
            }
            start=current.link;
            if(getCount()>1){
                // comparing caller with person going to be dead
              if(caller==current.data)
                    System.out.println("WTF!! I will have to kill myself ! :( "
                                  +deleteNode(current));
            else    
              System.out.println("I do not want to say but you must die Mr. no:"
                                   +deleteNode(current));
            }else{
                System.out.println("Thank God ! I saved myself :)");
                break;
                }
           
            current=start;
        }
    }
    private static class Node{
    int data;
    Node link;
    public Node(int data){
        this.data=data;
    }
    @SuppressWarnings("unused")
    public Node(int data,Node link){
        this.data=data;
        this.link=link;
    }
   }
}


Pointing upCode for main class:

package techy.rajeev;

import java.util.Scanner;

public class Josephus {
    private CircularLinkedList cl;
    private int noOfPersons;
    private int countToDeath;
    public void setInts(){
        System.out.print("Enter the no. of people:");
        Scanner in=new Scanner(System.in);
        noOfPersons=in.nextInt();
        System.out.print("Enter the count to death:");
        countToDeath=in.nextInt();
    }
    public void buildCircularLinkedList(){
        cl=new CircularLinkedList();
        for(int i=1;i<=noOfPersons;i++)
            cl.append(i);
        cl.displayList();
    }
    public void startTheGame(){
        cl.game(countToDeath, noOfPersons);
        System.out.print("Lucky fellow was:");cl.displayList();
    }
    public static void main(String args[]){
        Josephus js=new Josephus();
        js.setInts();
        js.buildCircularLinkedList();
        js.startTheGame();
        
    }
    
}
Pointing upOutput for a test case:

Enter the no. of people:7

Enter the count to death:3

-> 1
2
3
4
5
6
7 ->
1Says->I do not want to say but you must die Mr. no:4

5Says->I do not want to say but you must die Mr. no:1

2Says->I do not want to say but you must die Mr. no:6

7Says->I do not want to say but you must die Mr. no:5

7Says->WTF!! I will have to kill myself ! :( 7

2Says->I do not want to say but you must die Mr. no:3

2Says->Thank God ! I saved myself :)

Lucky fellow was:->2 ->

More on this at techcresendo.com

Read More ->>
DMCA.com Protected by Copyscape Online Plagiarism Tool