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

 largecover

Complete program

Putting all of this together gives:

package guess;
import java.io.IOException;

public class Guess {

 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" + 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("?");
  do {
   ans = (char) System.in.read();
  }
  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

throws java.io.IOException

and the

import java.io.IOException;

at the start 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. It is a fact that the more Java you know the easier things are to write.

You should also notice that this simple program was in fact quite difficult to implement because of all of the tiny details that you needed to know to make it work.

Learning any programming language 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

largecover

Contents

  1. Why Java?
  2. Getting started with Java
  3. Introducing Java - Swing Objects
  4. Writing Code
  5. Command Line Programs
  6. User Interface - More Swing
  7. Working With Class
  8. Java Class Inheritance
  9. Java Data Types - Numeric Data
  10. Java Data Types - Arrays And Strings
  11. Building a Java GUI - Containers
  12. Advanced OOP - Type, Casting, Packages
  13. Value And Reference 
  14. Java Lambdas, SAMs And Events

 

 

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

graphics

 



 

Comments




or email your comment to: comments@i-programmer.info

 

<ASIN:0072263148>