Java
/* --- Guess what number im thinking for Java.
--- E.K.Virtanen 2013, public domain --- */
import java.util.Random;
import java.util.Scanner;
public class Guess{
// method that clears the screen.
public static void clearScr() {
for(int i = 0; i < 50; i++) {
System.out.println();
}
}
// method that generates random integer between 0 and "int max"
public static int randomNumber(int max){
int randomInteger;
Random randomGenerator = new Random();
if (max > 0) {
randomInteger = randomGenerator.nextInt(max);
} else {
randomInteger = 0;
}
return randomInteger;
}
// method that checks player guess and returns false/true
public static boolean isCorrect(int guess, int correct) {
if (guess == correct) {
return true;
} else {
return false;
}
}
// method that returns "lower/higher" depending of player guess
public static String hiLo(int guess, int correct) {
if (guess < correct) {
return "higher.";
} else {
return "lower.";
}
}
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
final int MAX;
MAX = 100; // max value
int number; // number player tries to guess
number = randomNumber(MAX);
int guess; // player guess
int counter; // how many
counter = 0;
clearScr();
System.out.println("Welcome to play \"Guess the number\"");
System.out.println();
System.out.println("Cpu just randomed a number between 1 and 100.");
System.out.println("Your job is to guess which number it is.");
System.out.println("While you play, i give you a tips was your guess too high or low.");
System.out.println();
System.out.println("You can exit game by guessing 0 or higher than 100.");
System.out.println();
do { // guess <> number && guess < 101 && guess > 0
counter++;
System.out.println("This is round number: " + counter + ".");
System.out.println("What is your guess (1 - 100): ");
guess = lukija.nextInt();
if (guess > 0 && guess < 101) {
if (isCorrect(guess, number)) {
System.out.println("HOORAY!!! You got it!!!");
System.out.println("It took " + counter + " rounds.");
} else {
System.out.print("Try " + hiLo(guess, number));
}
}
} while( guess != number && guess < 101 && guess > 0);
}
}