Java program – Interactive user input

by Nideesh C on April 28, 2011 · 0 comments

in Java Programming




public class TwentyQuestions {

    public static void main(String[] args) {

        // Generate a number and answer questions
        // while the user tries to guess the value.
        int N = 1 + (int) (Math.random() * 1000000);

        StdOut.print("I'm thinking of a number ");
        StdOut.println("between 1 and 1,000,000");
        int m = 0;
        while (m != N) {

            // Solicit one guess and provide one answer
            StdOut.print("What's your guess? ");
            m = StdIn.readInt();
            if (m == N) StdOut.println("You win!");
            if (m < N)  StdOut.println("Too low ");
            if (m > N)  StdOut.println("Too high");
        }
    }
} 


/*************************************************************************
 *  Dependencies  StdIn.java
 *
 *  % java TwentyQuestions
 *  I'm thinking of a number between 1 and 1,000,000
 *  What's your guess? 500000
 *  Too high
 *  What's your guess? 250000
 *  Too low
 *  What's your guess? 375000
 *  Too high
 *  What's your guess? 312500
 *  Too high
 *  What's your guess? 300500
 *  Too low
 *  ...
 *
 *************************************************************************/



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. Java program – Sieve of Eratosthenes
  2. Java program – While loop
  3. Java program – Integer multiplication and division
  4. Java program – Harmonic numbers
  5. Java program – Gambler’s ruin simulation

Leave a Comment

Previous post:

Next post: