Java Queries Here..

arnab.d287

Still A Student!!!
I wanted to create a game like the 15puzzle
15puzzle
Code:
import java.io.*;
class puzzle
{
    int a[][]={{8,2,7,4},{1,11,0,10},{15,3,12,5},{14,6,13,9}};
    int n; int r=0; int c=0;
    public void main()throws IOException
    {
        display();
        
        do
        {         
            input();
            swapping(a, r, c);
            checkForCompletion();
            display();
        }while(true);
    }
    public void input()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the number to move");
        System.out.println("Enter 0 to exit");
        n=Integer.parseInt(br.readLine());
        
        int flag=0;
        int c=0,r=0;
        
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(n==a[i][j])
                {
                    r=i;
                    c=j;
                    flag=1;
                    break;
                }
            }
        if(n<1&&n>15)
            System.out.println("Invalid Input");
        else if (flag!=1)
            System.out.println("Invalid Input");
        else if(n==0)
            System.exit(0);
    }
    public void swapping(int a[][], int r, int c)
    {
        int fl=0;
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(r!=3||a[r+1][c]==0)
                {
                    a[r+1][c]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=0||a[r-1][c]==0)
                {
                    a[r-1][c]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=0||a[r][c-1]==0)
                {
                    a[r][c-1]=n;fl=1;
                    a[r][c]=0;
                }
                else if(r!=3||a[r][c+1]==0)
                {
                    a[r][c+1]=n;fl=1;
                    a[r][c]=0;
                }
                
            }
        if(fl!=1)
            System.out.println("Cannot be moved");
        
    }
    public void checkForCompletion()
    {
        int c=1;int fl=0;
        for (int i=0;i<4;i++)
            for(int j=0;j<4;j++)
            {
                if(i!=4&&j!=4)
                {
                    if(a[i][j]!=c++)
                        fl=1;
                }
            }
        if (fl==0)
        {
            System.out.println("Completed");
            System.exit(0);
        }
        
    }
   
    public void display()
    {
        for (int i=0;i<4;i++)
        {
            for(int j=0;j<4;j++)
            {
                System.out.print(a[i][j]+"  ");
            }
            System.out.println();
        }
    }
}
I used the blank space as 0(zero) for the game
but it is not running as it should be.. Can anyone tell whats wrong?
 

Garbage

God of Mistakes...
^^ Sorry if it's the spoiler for you, but I found the program pretty interesting and wrote a solution for that.

Here is the code: *pastie.org/2865669

Code:
import java.io.*;

/**
 * A puzzle game
 * @author Shirish Padalkar
 *
 */
public class Puzzle {
	
	/**
	 * Reader to read numbers from standard input
	 */
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	/**
	 * Main method which handles the puzzle. The flow of the puzzle is as following:
	 * <ol>
	 * 	<li>Display the current state of puzzle</li>
	 *  <li>If puzzle is not completed, ask for a number to move.</li>
	 *  <li>Check if the number is in valid input range.</li>
	 *  <li>Check if the number can be moved. If yes, then move the number, else show error message. Go to step 2.</li>
	 *  <li>Move the number.</li>
	 *  <li>Go to step 1</li>
	 * </ol>
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		
		/**
		 * Array to hold the numbers of the puzzle.
		 */
		int[][] array = { 
				{ 8, 2, 7, 4 },
				{ 1, 11, 0, 10 },
				{ 15, 3, 12, 5 },
				{ 14, 6, 13, 9 }
			};
		
		/*int[][] array = { 
				{ 1, 2, 3, 4 },
				{ 5, 6, 7, 8 },
				{ 9, 10, 11, 12 },
				{ 13, 14, 0, 15 }
			};*/
		
		boolean completed = false, validInput = false;
		int number;
		
		System.out.println("Welcome to Puzzle. Please enter 0 to exit.");
		display(array);

		while (!completed){
			number = input();
			if (number == 0){
				System.exit(0);
			}
			
			validInput = isValidInput(array, number);
			if (!validInput){
				System.err.println("Invalid Input");
				continue; // Skip the swapping. Ask for input again.
			}
			
			// A number must be swapped by now. If not, then throw error.
			if (!swap(array, number)){
				System.err.println("The number you entered can't be moved.");
			}
			
			display(array);
			
			completed = checkForCompletion(array);
		}
		
		System.out.println("Congratulations! You have successfully completed the puzzle. :)");
	}

	/**
	 * A method to display the puzzle current state
	 * @param array Current state of the puzzle
	 */
	private static void display(final int[][] array) {
		System.out.println("---------------------");
		for (int i = 0; i < 4; i++) {
			System.out.print("| ");
			for (int j = 0; j < 4; j++) {
				System.out.print((array[i][j] == 0?"  ":(array[i][j]<10?" "+array[i][j]:array[i][j])) + " | ");
			}
			System.out.println("\n---------------------");
		}
	}
	
	/**
	 * A method to get a number to move in the puzzle
	 * @return number accepted. 0 in case of invalid input (Exception)
	 */
	private static int input(){
		System.out.print("Enter the number to move : ");
		int num = 0;
		try{
			num = Integer.parseInt(br.readLine());
		} catch(IOException e){
			System.err.println("Invalid input. Not a number!");
		}
		return num;
	}
	
	/**
	 * A method to check if user input number is valid
	 * @param array current state of the puzzle
	 * @param number number to check if present in the puzzle
	 * @return
	 */
	private static boolean isValidInput(final int[][] array, int number){
		if (number < 1 && number > 15)
			return false;

		// Check if the number is present in the puzzle, so that we can move
		for (int i = 0; i < 4; i++){
			for (int j = 0; j < 4; j++) {
				if (number == array[i][j]) {
					return true;
				}
			}
		}
		return false;
	}

	
	/**
	 * A method to swap the number with empty column
	 * @param array Current state of the puzzle
	 * @param number number to swap with
	 * @return true if number is swapped. false if can't be swapped
	 */
	private static boolean swap(final int[][] array, int number) {
		// Determine the position of the "number to be swapped" in the matrix
		int row=0, column=0;
		boolean found = false;
		for (row=0; !found && row<4; row++){
			for (column=0; !found && column<4; column++){
				if(array[row][column] == number){
					found = true;
					//System.out.println("Found number at position "+row+"["+column+"]");
					break;
				}
			}
		}
		row--; //decremented row because once we broke from inner loop, program did row++ and then check the condition !found && row<4
		if (!found){
			System.err.println("Invalid number");
			return false;
		}
		
		boolean swapped = false;
		// row[column] now holds the number, check if any adjacent value is 0 so that we can swap
		// A number can be swapped only if any of left/right/top/bottom value is 0
		if (column > 0){ // Can check left
			//System.out.println("row: "+row+", column: "+column+", checking left");
			if (array[row][column-1] == 0){ // Got empty at left. Can swap
				array[row][column-1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && column < 3){ // Can check right
			//System.out.println("row: "+row+", column: "+column+", checking right");
			if (array[row][column+1] == 0){ // Got empty at left. Can swap
				array[row][column+1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row > 0){ // Can check top
			//System.out.println("row: "+row+", column: "+column+", checking top");
			if (array[row-1][column] == 0){ // Got empty at left. Can swap
				array[row-1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row < 3){ // Can check bottom
			System.out.println("row: "+row+", column: "+column+", checking bottom");
			if (array[row+1][column] == 0){ // Got empty at left. Can swap
				array[row+1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		return swapped;
	}

	
	/**
	 * A method to check if the puzzle is completed
	 * @param array current state of the puzzle
	 * @return true if puzzle is completed. false otherwise
	 */
	private static boolean checkForCompletion(final int[][] array) {
		
		//System.out.println("Checking for completion.");
		int counter = 1;
		
		for (int row = 0; row < 4; row++){
			for (int column = 0; column < 4 && counter < 16; column++, counter++) {
				if (array[row][column] != counter){
					//System.out.println("Not completed because value of puzzle["+row+"]["+column+"] is "+array[row][column]+", not "+counter);
					return false;
				}
			}
		}
		return true; // Control will come here only if everything is fine.
	}
}
 
Last edited:

arnab.d287

Still A Student!!!
^^ Sorry if it's the spoiler for you, but I found the program pretty interesting and wrote a solution for that.

Here is the code: #2865669 - Pastie

Code:
import java.io.*;

/**
 * A puzzle game
 * @author Shirish Padalkar
 *
 */
public class Puzzle {
	
	/**
	 * Reader to read numbers from standard input
	 */
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	/**
	 * Main method which handles the puzzle. The flow of the puzzle is as following:
	 * <ol>
	 * 	<li>Display the current state of puzzle</li>
	 *  <li>If puzzle is not completed, ask for a number to move.</li>
	 *  <li>Check if the number is in valid input range.</li>
	 *  <li>Check if the number can be moved. If yes, then move the number, else show error message. Go to step 2.</li>
	 *  <li>Move the number.</li>
	 *  <li>Go to step 1</li>
	 * </ol>
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		
		/**
		 * Array to hold the numbers of the puzzle.
		 */
		int[][] array = { 
				{ 8, 2, 7, 4 },
				{ 1, 11, 0, 10 },
				{ 15, 3, 12, 5 },
				{ 14, 6, 13, 9 }
			};
		
		/*int[][] array = { 
				{ 1, 2, 3, 4 },
				{ 5, 6, 7, 8 },
				{ 9, 10, 11, 12 },
				{ 13, 14, 0, 15 }
			};*/
		
		boolean completed = false, validInput = false;
		int number;
		
		System.out.println("Welcome to Puzzle. Please enter 0 to exit.");
		display(array);

		while (!completed){
			number = input();
			if (number == 0){
				System.exit(0);
			}
			
			validInput = isValidInput(array, number);
			if (!validInput){
				System.err.println("Invalid Input");
				continue; // Skip the swapping. Ask for input again.
			}
			
			// A number must be swapped by now. If not, then throw error.
			if (!swap(array, number)){
				System.err.println("The number you entered can't be moved.");
			}
			
			display(array);
			
			completed = checkForCompletion(array);
		}
		
		System.out.println("Congratulations! You have successfully completed the puzzle. :)");
	}

	/**
	 * A method to display the puzzle current state
	 * @param array Current state of the puzzle
	 */
	private static void display(final int[][] array) {
		System.out.println("---------------------");
		for (int i = 0; i < 4; i++) {
			System.out.print("| ");
			for (int j = 0; j < 4; j++) {
				System.out.print((array[i][j] == 0?"  ":(array[i][j]<10?" "+array[i][j]:array[i][j])) + " | ");
			}
			System.out.println("\n---------------------");
		}
	}
	
	/**
	 * A method to get a number to move in the puzzle
	 * @return number accepted. 0 in case of invalid input (Exception)
	 */
	private static int input(){
		System.out.print("Enter the number to move : ");
		int num = 0;
		try{
			num = Integer.parseInt(br.readLine());
		} catch(IOException e){
			System.err.println("Invalid input. Not a number!");
		}
		return num;
	}
	
	/**
	 * A method to check if user input number is valid
	 * @param array current state of the puzzle
	 * @param number number to check if present in the puzzle
	 * @return
	 */
	private static boolean isValidInput(final int[][] array, int number){
		if (number < 1 && number > 15)
			return false;

		// Check if the number is present in the puzzle, so that we can move
		for (int i = 0; i < 4; i++){
			for (int j = 0; j < 4; j++) {
				if (number == array[i][j]) {
					return true;
				}
			}
		}
		return false;
	}

	
	/**
	 * A method to swap the number with empty column
	 * @param array Current state of the puzzle
	 * @param number number to swap with
	 * @return true if number is swapped. false if can't be swapped
	 */
	private static boolean swap(final int[][] array, int number) {
		// Determine the position of the "number to be swapped" in the matrix
		int row=0, column=0;
		boolean found = false;
		for (row=0; !found && row<4; row++){
			for (column=0; !found && column<4; column++){
				if(array[row][column] == number){
					found = true;
					//System.out.println("Found number at position "+row+"["+column+"]");
					break;
				}
			}
		}
		row--; //decremented row because once we broke from inner loop, program did row++ and then check the condition !found && row<4
		if (!found){
			System.err.println("Invalid number");
			return false;
		}
		
		boolean swapped = false;
		// row[column] now holds the number, check if any adjacent value is 0 so that we can swap
		// A number can be swapped only if any of left/right/top/bottom value is 0
		if (column > 0){ // Can check left
			//System.out.println("row: "+row+", column: "+column+", checking left");
			if (array[row][column-1] == 0){ // Got empty at left. Can swap
				array[row][column-1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && column < 3){ // Can check right
			//System.out.println("row: "+row+", column: "+column+", checking right");
			if (array[row][column+1] == 0){ // Got empty at left. Can swap
				array[row][column+1] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row > 0){ // Can check top
			//System.out.println("row: "+row+", column: "+column+", checking top");
			if (array[row-1][column] == 0){ // Got empty at left. Can swap
				array[row-1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		if (!swapped && row < 3){ // Can check bottom
			System.out.println("row: "+row+", column: "+column+", checking bottom");
			if (array[row+1][column] == 0){ // Got empty at left. Can swap
				array[row+1][column] = array[row][column];
				array[row][column] = 0;
				swapped = true;
			}
		}
		return swapped;
	}

	
	/**
	 * A method to check if the puzzle is completed
	 * @param array current state of the puzzle
	 * @return true if puzzle is completed. false otherwise
	 */
	private static boolean checkForCompletion(final int[][] array) {
		
		//System.out.println("Checking for completion.");
		int counter = 1;
		
		for (int row = 0; row < 4; row++){
			for (int column = 0; column < 4 && counter < 16; column++, counter++) {
				if (array[row][column] != counter){
					//System.out.println("Not completed because value of puzzle["+row+"]["+column+"] is "+array[row][column]+", not "+counter);
					return false;
				}
			}
		}
		return true; // Control will come here only if everything is fine.
	}
}


Thanks.. I found out the missing link..

Thanks Garbage...
 
Java Code retrieving from DB

Guys can someone help me with Java code that can be used to connect to a DB and retrieve from the DB.
Scenario-->
1) A user interface where it asks the user to enter an item (say chocolates, veggies etc..)
2) After user input, it checks the DB (which already has some predefined list of items) and if an item match occurs, it must display in an alert box that the item match is found.

I am a newbie in Java. So kindly provide me the full code if possible.
 

Garbage

God of Mistakes...
^^ To access database using Java, please read following tutorial:
Trail: JDBC(TM) Database Access (The Java™ Tutorials)
 
To access database using Java, please read following tutorial:


Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?
 

Piyush

Lanaya
Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?
well you need something to "follow" your instruction
thats what button object is doing there
rest of all is the concept of JDBC
 

Garbage

God of Mistakes...
Yes i followed the tutorial. I could now understand that i need to create a connection first, but this connection must be established only when i click on a button object in Java (JButton). How can i establish a database connection using button objects.?

After a click of button, create an instance of the your connection class and use it for your database activities.
 

arnab.d287

Still A Student!!!
Can anyone give me some programs to work on?? I have limited knowledge to Inheritance, Linked list, string, array.. I have only used io package in my progs.. So according to it some progs to test my skill will be welcome.. I have practiced all textbook programs. Any suggestion..?? I need the question only.. Thanks in advance
 

Liverpool_fan

Sami Hyypiä, LFC legend
Can anyone give me some programs to work on?? I have limited knowledge to Inheritance, Linked list, string, array.. I have only used io package in my progs.. So according to it some progs to test my skill will be welcome.. I have practiced all textbook programs. Any suggestion..?? I need the question only.. Thanks in advance

Project Euler
 

Prime_Coder

I'm a Wannabe Hacker
@ Piyush
The revised edition of the classic "Core Java: Volume II–Advanced Features" , covers advanced user-interface programming and the enterprise features of the Java SE platform.

For SCJP preparation, the best book in my opinion is "SCJP Sun Certified Programmer for Java" by Kathy Sierra and Bert Bates, but don't know how much it will be relevant for the next exam version (Java 7).
Another better option would be "A Programmer's Guide to Java Preparation" by Khalid Mughal and Rolf Rasmussen.
Hope this helps you.
 

buddyram

New Voyage
My java program gets compiled but while running the program i get to see the below error message:


Error Message:
C:\>cd jdk/bin

C:\jdk\bin>javac boxarea.java

C:\jdk\bin>java boxarea
Exception in thread "main" java.lang.NoClassDefFoundError: boxarea (wrong name:
Boxarea)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
2)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

Code:
import java.io.*;

class Box {

double width;

double height;

double length;

void getdata( double x,double y, double z) {

width = x;

height = y;

length = z;

}

double volume( ) {

return(width*height*length);

}

}

class Boxarea {

public static void main(String args[ ]) {

double v1,v2;

Box b1= new Box( );

Box b2 = new Box( );

b1.width=2;

b1.height=4;

b1.length=8;

b2.getdata(5,10,15);

v1=b1.volume();

v2=b2.volume();

System.out.println("The volume1 is = " +v1);

System.out.println("The volume2 is= " +v2);

}

}

I haven't set any path
i am running the program from c:\jdk\bin
 
Last edited:

sakumar79

Technomancer
I havent touched java programming in years (not a programmer by profession) but dont the variables of a class take private behaviour unless defined specifically as public? Try adding public to length, width and height variable declaration in box class...

Arun
 

buddyram

New Voyage
those variables are accessed by the objects of that particular, so i don't think the access modifiers should be made public.
the problem is in setting the path for the class files, i googled and checked but

set CLASSPATH=.;C:\;
checked the above command but nothing changed!

. . . and moreover if that was the error then it should have shown at compile time
 

sakumar79

Technomancer
But you are setting b1's variables from outside the Box class (b1.width=2, etc). You can try and see if it helps...

Anyway, its long since I programmed with java, so I will let others more conversant help you out...

Arun
 

Prime_Coder

I'm a Wannabe Hacker
My java program gets compiled but while running the program i get to see the below error message:


Error Message:
C:\>cd jdk/bin

C:\jdk\bin>javac boxarea.java

C:\jdk\bin>java boxarea
Exception in thread "main" java.lang.NoClassDefFoundError: boxarea (wrong name:
Boxarea)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
2)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

Code:
import java.io.*;

class Box {

double width;

double height;

double length;

void getdata( double x,double y, double z) {

width = x;

height = y;

length = z;

}

double volume( ) {

return(width*height*length);

}

}

class Boxarea {

public static void main(String args[ ]) {

double v1,v2;

Box b1= new Box( );

Box b2 = new Box( );

b1.width=2;

b1.height=4;

b1.length=8;

b2.getdata(5,10,15);

v1=b1.volume();

v2=b2.volume();

System.out.println("The volume1 is = " +v1);

System.out.println("The volume2 is= " +v2);

}

}

I haven't set any path
i am running the program from c:\jdk\bin

The program code works well on my system. :razz:
I'm still figuring out what might be the problem at your side.
 

buddyram

New Voyage
@Prime_Coder:
now the program is working fine
OMG, the filename and the classname were not of the same CASE!

after a long time i was working on java, so i couldn't notice this!
one of my friend helped me in sorting out this bug

thanks for your support
 
Top Bottom