Java - Command Line Programs
Written by Mike James   
Article Index
Java - Command Line Programs
Data Types
Operators And An Example
The Complete Program

Operators

Variables of different types are just half of the story. The key idea is that the data that you store in variables can be used in computations with the help of suitable operators. In this section we look at simple arithmetic operators which allow you to perform standard arithmetic but as you learn more Java you will learn about other types of operator that can be used to combine data types that are not numeric. 

When it comes to operations with numeric variables you can use the usual +.-,* and / symbols to mean add, subtract, multiply and divide.

Notice that what operators you can use depends on the type of the data you are trying to operate on - numeric operators can only work with numeric variables. Put in this way this seems obvious but you will still probably make the mistake of trying to add two characters that just happen to look like numbers. That is '1'+'2' will fail with an error but 1+2 will work perfectly. 

Notice that you can use parentheses to make up very complicated looking operator expressions. For example:

answer=(a+b/2+c*100)/3;

An expression is like a mini-program defining how to combine values and variables to get a result. In practice you need to careful that any long expressions you enter really do compute what you think they do.

There are also a few more advanced arithmetic operators for example you will see ++ and -- in programs quite a lot.

You can also use ++ and - - to mean increment and decrement. The expression:

a++;

is the same as:

a=a+1;

and 

a--

is the same as:

a=a-1;

For example, after:

a=10;
b=10;
a++;
b--;

a contains 11 and b contains 9.

An advanced detail is when the increment or decrement actually occurs. If you increment or decrement a variable in an expression the value that is used depends on whether you place the ++ or - - in front or behind the variable. If the ++ or - - is in front then the operation is done first and if behind it is done after.

For example:

a=10;b=++a;

stores 11 in b and in a, but:

a=10;b=a++;

stores 10 in b and 11 in a.

If you find this confusing then the moral is - don’t get carried away with the use of ++ and - -

It is very easy to create complex and confusing expressions using them.

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.

To do this we will have to introduce some Java instructions that we haven't met before but these are just generalizations of things we already know. 

Number guess 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.

guess=lower+(upper-lower)/2

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. Notice that guess is worked out using a numerical expression with variables and operators.

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. 

We are also going to be 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.

All of these control statements have been discussed in the previous chapter but it takes time to learn how to use them properly.

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 System.in.read() 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:

ans=(char) System.in.read();

will store the next character typed at the keyboard in it. The (char) can be thought of as an instruction to convert the integer that System.in.read() returns into a character.

If only life were that easy!

There is yet another complication.

System.in.read 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 System.in.read 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') {
 guess=lower+(upper-lower)/2;
  System.out.println("Is your number
                              "+guess);
  System.out.println("Answer One of ");
  System.out.println("Y(es)");
  System.out.println("B(igger)");
  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:

do{
 ans=(char) System.in.read();
}while(ans=='\n');

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!!");

}