Get started Bring yourself up to speed with our introductory content.

This Java programming example will help you learn the language

Learning Java in a way that is both fun and effective is possible. In this tutorial, we take a problem-based approach to developing a stand-alone Java application.

The best way to learn any programming language quickly is to run through a set of tutorials and exercises that require you to solve a given problem. A problem-based approach is always the best way to learn. In this Java programming example, we look at how a Java developer might tackle the challenge of creating a stand-alone Java application that plays an interactive rock-paper-scissors game.

A problem-based approach is always the best way to learn.

What would a simple game of rock-paper-scissors, or roshambo as it is otherwise known, look like when developed, in its simplest form, as a Java application? Let's look at the basic syntax of a Java class to see how we can create an application that runs and meets the stated business requirements.

Reviewing the roshambo business requirements

Here are the basic business requirements:

  • The user will type in either rock, paper or scissors
  • To simplify development and testing, the server will always choose rock
  • Rock beats scissors, scissors beats paper and paper beats rock
  • A text error will be displayed if the user does not enter rock, paper or scissors into the entry field

Creating the Java class

To solve this problem in Java, you first must create a Java class. One of the tautological rules of Java is that everything is coded within a Java class, with some exceptions. There are special components like Enums and Interfaces that don't use Java class semantics, but otherwise, every piece of code in Java must go within a Java class. So, a Java class is a must:

public class Roshambo {

     //code goes here

}

Coding the main method

Any code you plan to run has to go in a special method named main. Java's main method must be decorated with the keywords public, static and void, and it must take an array of Strings as an argument. The main method in the Java programming example looks like this:

public class Roshambo {

     public static void main(String args[]) {

           //code to run goes here

     }

}

A good programming practice is to declare any variables you might need at the start of the method. In our Java programming example, we use four variables of type String named prompt, clientGesture, serverGesture and outcome.

public class Roshambo {

     public static void main(String args[]) {

           //variable declarations

           String prompt = "Will it be rock, paper or scissors?";

           String clientGesture = null;

           String serverGesture = "rock";

           String outcome = "error";

     }

}

Digging into the Swing packages

To garner input from the user and display the outcome, we can use two different JOptionPane dialog boxes that will need to be imported from a special Java library that makes graphic programming easy. The library is known as the javax.swing package. The showInputDialog method of the JOptionPane class will prompt for the input, and the showMessageDialog will be used to display the output.

import javax.swing.*;

public class Roshambo {

     public static void main(String args[]) {

           String prompt = "Will it be rock, paper or scissors?";

           String clientGesture = null;

           String serverGesture = "rock";

           String outcome = "error";

           clientGesture = JOptionPane.showInputDialog(prompt);

           //conditional logic goes here

           JOptionPane.showMessageDialog(null, outcome);

     }

}

Implementing conditional logic in Java

We still need conditional logic to determine whether the game resulted in a win, loss or tie. Right now, if we play the game, no matter what is typed into the input field, the output would always result in an error, as the input dialog and message dialog boxes in Figure 1 show.

Running the program before implementing the conditional logic.
Figure 1. Running the program before implementing the conditional logic.

Given that the server always chooses rock, the conditional logic is relatively straight forward, with three simple if statements fulfilling the business requirements:

import javax.swing.*;

public class Roshambo {

     public static void main(String args[]) {

           String prompt = "Will it be rock, paper or scissors?";

           String clientGesture = null;

           String serverGesture = "rock";

           String outcome = "error";

           clientGesture = JOptionPane.showInputDialog(prompt);

           if (clientGesture.equalsIgnoreCase("rock")) {

                outcome = "tie";

           }

           if (clientGesture.equalsIgnoreCase("scissors")) {

                outcome = "loss";

           }

           if (clientGesture.equalsIgnoreCase("paper")) {

                outcome = "win";

           }

           JOptionPane.showMessageDialog(null, outcome);

     }

}

Running the application

To run the application, the code first needs to be compiled into byte-code, which then is executed by the JVM.

C:\_jdk1.8\bin>javac Roshambo.java

C:\_jdk1.8\bin>java Roshambo

When we cycle through the four different input scenarios, namely paper, scissors, rock and some nonsensical input, we get the expected outcomes of win, loss, tie and error, respectively. Figure 2 shows the rock scenario.

A successful run of the roshambo application.
Figure 2. A successful run of the roshambo application.

And that demonstrates how to write, compile and run a simple Java program that plays a highly simplified version of the classic rock-paper-scissors game. In subsequent articles in this series, further iterations will add iterative logic, object orientation and even persistence. This version of the game is also available in Ruby and JavaScript versions; if you want to learn those languages quickly as well, review the corresponding tutorials presented in this series of articles to see how the world behaves when a JVM isn't the target runtime.

If you want to challenge yourself and reinforce your learning, try these exercises:

  1. Rework the conditional logic to use if-else blocks instead of using only ifs.
  2. Rework the conditional logic to use a switch statement instead of if statements.

How would you improve the code developed in this example? Let us know.

Modern programming languages made easy for Java developers

For those interested in learning Java, or for those who know Java and are interested in leveraging those skills in order to learn a complimentary language like JavaScript or Ruby, TheServerSide is providing a number of problem-driven tutorials that will help you master the fundamentals of these languages.

The catalog of tutorials currently includes the following:

This was last published in January 2016

Dig Deeper on Software programming languages

PRO+

Content

Find more PRO+ content and other member only offers, here.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchCloudApplications

SearchSoftwareQuality

SearchFinancialApplications

SearchSAP

SearchManufacturingERP

Close