Java to write a number guessing game

  • 2020-04-01 04:12:52
  • OfStack

The example of this article describes the Java implementation of the simple guess number game code. Share with you for your reference.

The following is a quote from a guessing number game written in the Java language:


 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Scanner;
 
 //The main function
 public class calssOne {
 
 public static void main(String[] args) {
  
 //shit+Ctrl+o
 int result;
 //Randomly generate a number within 100
 int number = (int)(Math.random()*100);
 System.out.println("n*********** Guess the digital game, you hold Have to live? *********");
 System.out.println("n ******** Random number generation: don't tell you! *********n");
 System.out.println("n *********** The answer: "+number+"***************n");
 System.out.println(" Let's use our heads to take a guess, tip: he is an expert 1 to 100 The integer ");
 long sTartTime=System.currentTimeMillis();//Define a time variable
 for(int i=1;i<100;i++){
  System.out.println(" Please enter your number "+i+" Time of speculation ");
  result=calssOne.guess(i);//Get the input result by calling the input function
  //By comparing the output console
  if(result>number)
  System.out.println(" Sorry, the number you guessed is greater than the answer to the riddle !");
  else if(result < number)
  System.out.println(" Sorry, the number you guessed is less than the answer to the riddle !");
  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! A medium !!");
  }
  else if(i<10){
   System.out.println("good job!  You guessed it all "+i+" time ,  And keep going !!");
  }
  else{
   System.out.println("not bad!  You guessed it all "+i+" time ,  A long way to go! ");
  }
  System.out.println(" The current time  :" +sNowDate.format(new Date()));//New Date() to get the current system time
  //System.out.println(" current time :" +sNowDate);
  System.out.println(" The time used  :" +(sEndTime-sTartTime)/1000+" seconds ");
  return;
  }
 }
 }
 //Input function
 public static int guess(int i){
  //By importing the java.util.Scanner class package
 Scanner sc=new Scanner(System.in);
 int result;
 try{
  //Causes input in the console to be numeric
  result=sc.nextInt();
  return result;
 }
 catch (Exception e) {
  // TODO: handle exception 
 System.out.println(" What you put in is not a word , Please enter the number again "+i+" A digital ");
 //Call this function to re-enter
 guess(i);
 }
 return 0;
 }
 }

Java language to write a guess the number of small game function, to share with you! For those of you who have just learned programming, I hope this article will be helpful to you in your Java programming.


Related articles: