Java - Command Line Programs
Java - Command Line Programs
Written by Ian Elliot   
Wednesday, 30 May 2012
Article Index
Java - Command Line Programs
Data Types
Try It Out - Java Guess

Java Guess



In Writing Java Code - Methods we looked at the basics of Java in terms of the instructions used to build a program - if, while, for and so on.  Now we've seen the basic data types that Java supports and been introduced to using Swing and the command line to interact with the user. It is time for a small example.

At this stage in learning any programming language it is difficult to find any convincing demonstration program and in the case of Java this is particularly so. You need to know a lot of Java and its frameworks like Swing to do anything impressive. 

To show you a little more of how Java works let's implement an old favourite - number guess.

This works by asking you to pick a number between 1 and 100 and it then offers guesses as to the number you thought of.

The guessing procedure isn’t random, but a simple binary search. The program starts of with the full range of numbers from lower=1 to upper=100 and works out a guess in the middle of the range i.e.


It then asks if this is the number you have thought of. If the answer is Yes then the game is over but if it isn’t it asks if the number you are thinking of is bigger or smaller.

Using this information the program adjusts the range from upper to lower accordingly, i.e. either upper=guess or lower=guess, and the whole process repeats.

To implement this in Java we need to use a number of facilities that we haven’t discussed in detail and we need to use the control commands introduced in the previous chapter. 

In particular you can repeat a block of code using

while(condition){block of instructions}

which will repeat the block until the condition is false, i.e. the loop keeps going “while the condition is true”. There is also an alternative form of loop:

do {block of instructions} while(condition)

which will always carry out the block of instructions at least once. Contrast this to the first loop which, if the condition is initially false, will skip the block altogether.

We also need a conditional statement that will carry out an instruction only if a condition is true. This is the Java if statement, the simplest form of which is:

if(condition) {block of instructions}

which will only carry out the block of instructions if the condition is true.

Finally, we also need some way to get input from the user. In previous examples we have used the command System.out.println() to print something on the screen.

The equivalent input command is but the complication is that this returns a four-byte integer which corresponds to the key or character code. To store this as a character we need to use a type conversion operation called a “cast" - more of converting from one data type to another in a later chapter.

So if ans is a variable of type char the command:


will store the next character typed at the keyboard in it.

If only life were that easy! There is yet another complication. doesn’t return immediately you press the first key, it waits for you to type everything and then press carriage return. Then it returns with the first character on the line that you typed. When you next call it returns the second character and so on until it reaches the carriage return. What this means is, that even if we are only trying to read in a single character, you have to allow for the carriage return!

So start a new Java project called guess and first we declare the variable we are going to use:


public static void main(String[] args)
                    throws IOException {
 int upper = 100;
 int lower = 1;
 int guess;
 char ans = 'N';

In real life you probably wouldn't know all the variables you wanted to use before you wrote the rest of the program and you would go back and add each one as you discovered you needed it. 

Next we can print some helpful instruction to the user:

System.out.println("Think of a number between 1 and 100");

After this you need to make the program guess the number repeatedly until it gets it right:

while(ans!='Y') {
  System.out.println("Is your number
  System.out.println("Answer One of ");
  System.out.println( "S(maller)");
  System.out.print( "?");


This starts the loop which continues until the user answers with a Y. Notice that != is the Java way of saying "not equal to". A new guess is generated and displayed to the user along with a set of instructions as to what to do next.

The user is expected to type a single character followed by a return:


This do loop keeps on reading in until the user enters something other than a single return. Once again notice that '\n' means the return key.

Finally we can respond to what the user typed.

 if (ans =='B')lower=guess;
 if (ans =='S')upper=guess;

If it was a B then the lower bound is the guess, and if it was an S the upper bound is the guess.

If it was a Y then the loop comes to an end and we can congratulate ourselves:

 System.out.println("I guessed it!!");


Complete program

Putting all of this together gives:

public static void main(String[] args)
                    throws IOException {
 int upper = 100;
 int lower = 1;
 int guess;
 char ans = 'N';
 System.out.println("Think of a number
                    between 1 and 100");
 while (ans != 'Y') {
  guess = lower + (upper - lower) / 2;
  System.out.println("Is your number " +
  System.out.println("Answer One of ");
  do {
   ans = (char);
  } while (ans == '\n');
  if (ans == 'B') {
   lower = guess;
  if (ans == 'S') {
   upper = guess;

 System.out.println("I guessed it!!!");

If you type this program in then it should guess any number between 1 and 100 in the minimum number of guesses.

The only part of the program not explained even a little bit is the use of


which is all to do with picking up run time errors and it is something we will have to return to. I also have to admit that this program would be easier to write using strings, arrays and classes, but more of all of these in the next chapter.

You should also notice that this simple program was in fact quite difficult to write because of all of the tiny details that you needed to know to make it work. Learning any programming langauge is a lot like this. The broad picture is always the same but small details like != meaning not equal and /n meaning the return key vary and you have to get everything 100% right for anything to work.

Play with this example and see if you can improve on it. Try writing a program which accepts any two numbers and displays their sum. Next try to extend this to any number of numbers with the last number indicated by a zero.


Modern Java
With NetBeans And Swing



  1. Getting started with Java

    In chapter 1 we tell you how to get started with modern Java development in the shortest possible time. The approach uses NetBeans and Swing and all of the resources used are free to download and use.

  2. Introducing Java - Swing Objects
    In the second chapter of our beginner's guide to Modern Java we find out more about objects by exploring the Swing framework with a simple hands-on example.

  3. Writing Code

    Using ifs and loops is one of the most difficult parts of learning how to program. Our beginners introduction to Java reaches the part all programmers have know and know well - how to write code.

  4. Command Line Programs
    Command line programming means doing things in the simplest possible way. We take a careful look at how data types and code build a program.

  5. User Interface - More Swing
    Finding out how to create a User Interface (UI) using the Java Swing library is not only a useful skill, it also is an ideal way to learn about objects and to make sure that the ideas really have sunk in.

  6. Working With Class
    The Swing components have provided an easy approach to the idea of objects, but there comes a time when you have to find out how to create your own. In this part of Modern Java, we look at the standard ideas of object-oriented programming.

  7. Java Class Inheritance
    Working with classes and objects is a very sophisticated approach to programming. You can't expect to absorb all of its implications in one go. We have already looked at the basics of class and objects. Now we need to look at encapsulation, constructors, overloading and inheritance.

  8. Building a Java GUI - Containers
    In this chapter we get to grips with the idea of a container that is used to host components to build a user interface. We also find out how the Swing GUI Builder generates code to make it all much easier. 

  9. Java Data Types - Numeric Data
    After looking at some of the advanced ideas of classes and objects we need to return to some simpler topics to make our understanding complete. We need to look more closely at data and, to get things moving, numeric data. 



If you would like the code for this project then register and click on CodeBin.

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin,  or sign up for our weekly newsletter.

blog comments powered by Disqus

Last Updated ( Thursday, 09 June 2016 )

RSS feed of all content
I Programmer - full contents
Copyright © 2016 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.