This article describes the Java implementation of the simple guessing game code. Share to everyone for your reference.
The following is a reference fragment of a guess number game in the Java language:
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.Scanner;
Main function public class Calssone {public static void main (string[] args) {//shit+ctrl+o int result;
Randomly produces a number int = (int) (Math.random () *100) within 100; System.out.println ("\n*********** Guess digital games, you hold to live?"
*********"); System.out.println ("\ n ******** random number generation: Don't tell you!")
\ n ");
System.out.println ("\ n *********** Answer:" +number+ "***************\n");
SYSTEM.OUT.PRINTLN ("Let's use our brains to guess, little hint: He is an integer from 1 to 100"); Long Starttime=system.currenttimemillis ()///define a time variable for (int i=1;i<100;i++) {System.out.println ("Please enter your" +i+ "guess.
Measurement "); Result=calssone.guess (i)///by calling the input function to get input//through the comparison output console if (result>number) System.out.println ("Sorry, you guessed the number of
The word is greater than the answer number! ");
else if (Result < number) System.out.println ("Sorry, you guessed the figure is less than the answer number!");
else {SimpleDateFormat snowdate = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Long Sendtime=sYstem.currenttimemillis ();
System.out.println ("\ n *********** correct answer:" +number+ "***************\n"); if (i==1) {System.out.println ("perfect!! Congratulations to you!
One!! ");} else if (i<10) {System.out.println ("good job!
You have guessed the "+i+" time, but also to continue to refuel!! "); else{System.out.println ("Not bad! You have guessed "+i+" times, a long way!
"); System.out.println ("Current Time:" +snowdate.format (new date));//new Date () to get current system time//system.out.println ("current
Room: "+snowdate";
System.out.println ("Time used:" + (Sendtime-starttime)/1000+ "seconds");
Return }}//input function public static int guess (int i) {//By introducing Import Java.util.Scanner class package Scanner sc=new Scanner
(system.in);
int result;
try{//Make the input in the console must be a digital result=sc.nextint ();
return result;
catch (Exception e) {//Todo:handle Exception System.out.println ("You are not entering numbers, please re-enter the" +i+ "number");
Call this function to re-enter guess (i);
return 0;
}
}
The Java language to write a guess number games function, share to everyone! For those who have just learned to program, I hope this article will help you with your Java programming.