Without working on a small projects you won’t be able to utilize your coding ability. If you have basic knowledge about coding then also just try to work on small projects like calculator, age calculator, etc. because this will develop your interest on coding, otherwise you will feel bored (reason: coding is really boring and time consuming).
Work on such projects where simple logics are involved. Slowly increase the level of projects.
For this purpose only, i have written a code for a small project named “Guessing number game”. Well here, you have to guess the which the computer has generated. Here, you will know, after how many tries, you were able to guess it.
About code:
Its quite simple and easy to understand if you have basic knowledge about java coding. Within the main function i have written the logic behind the game.
Here, i have used random library to generate random values that you have to guess. And after that i have used looping function and its done.
logic:
Here, we have taken random values from 1 to 100. Within this range, computer will generate values and you have to guess number within this range ( you have increase or decrease the range as per your wish). When your guessing number is less than the generated random value than you just have to increase the your guessing number and vice versa. This logic will go on looping till you get correct value.
Here, i have used boolean value so as to find whether you get value or not.
Code:
// take random num
import java.util.Scanner;
import java.util.Random;
class guess{
public static void main(String[] args){
Scanner obj = new Scanner(System.in);
Random rand = new Random();
int numToGuess = rand.nextInt(100);
int noOfAttempts = 0;
int guessnum;
boolean status = false;
while(!status){
System.out.println("Guess the number: ");
guessnum = obj.nextInt();
noOfAttempts++;
if(guessnum < numToGuess){
System.out.println("You entered less number");
}else if (guessnum > numToGuess){
System.out.println("You entered greater number");
}else{
System.out.println("Congratulations!!, you guess the right number in "+ noOfAttempts + " attempts");
status = true;
}
}
obj.close();
}
}
Output:
