This article describes the simple number guessing game code implemented by Java. Share it for your reference.
The following is a reference clip of a number guessing game written in Java:
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; //Main function public class calssOne { public static void main(String[] ar gs) { //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 , can you hold it? ************"); System.out.println("/n ********* Random number generation: I won't tell you! ********* ***/n"); System.out.println("/n ************ Answer: "+number+"***************/ n"); System.out.println("Let's use our brains to guess, tip: it 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 guess of "+i+" time"); result=calssOne.guess(i);//By calling Input function gets the input result // Compare the output console if(result>number) System.out.println("Sorry, the number you guessed is greater than the answer number!"); else if(result < number) System.out .println("Sorry, the number you guessed is smaller than the answer number!"); else { SimpleDateFormat sNowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long sEndTime=System.current TimeMillis(); System.out.println("/n ************ Correct answer: "+number+"***************/n"); if(i ==1){ System.out.println("perfect!! Congratulations! win once!!"); } else if(i<10){ System.out.println("good job! You guessed "+i+" times in total, and you have to keep working hard!!"); } else{ System .out.println("not bad! You guessed "+i+" in total, and the journey is long!"); } System.out.println("Current time:" +sNowDate.format(new Date() ));// new Date() is to obtain the current system time //System.out.println("Current time:" +sNowDate); System.out.println("Elapsed time:" +(sEndTime-sTartTime)/1000 +"seconds"); return; } } } //Input function public static int guess(int i){ //By introducing the import java.util.Scanner class package Scanner sc=new Scanner(System.in); int result; try{ //Make the content entered in the console must be a number result=sc.nextInt(); return result; } catch (Exception e) { // TODO: handle exception System.out.println("What you entered is not a word , please re-enter the "+i+" number); //Call this function and re-enter guess(i); } return 0; } }A mini game that is written in Java language, I will share it with you! For students who have just learned programming, you can take a look. I hope this article will be helpful to everyone's Java programming design.