Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the game of guessing numbers by Java

Shulou Source: shulou.com Published: 2022-06-02 12:53:10 09月19日 Update

This article is to share with you about Java how to achieve the number guessing game, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Preface

In the past, when I was learning the C language, I did a number guessing game. These two days I learned the logical structure of Java and tried to use Java to achieve it.

I. C language version

The previous version of the C language.

Code # define _ CRT_SECURE_NO_WARNINGS#include # include # include void menu () {printf ("* *\ n"); printf ("* 1. Play 0.exit *\ n") Printf ("* *\ n");} void game () {int guess = 0; int r = rand ()% 100 + 1; while (1) {printf ("guessing numbers:"); scanf ("% d", & guess) If (guess > r) {printf ("guess big …") ;} else if (guess

< r) { printf("猜小了……"); } else { printf("猜对了!!!"); break; } }} int main(){ int input = 0; srand((unsigned int)time(NULL)); do { menu(); printf("输入你的选择:"); scanf("%d", &input); switch (input) { case 1: game(); break; case 0: printf("退出游戏"); break; default: printf("非法选择"); break; } } while (input); return 0;}运行结果 二、Java版本代码import java.util.Random;import java.util.Scanner;;public class guessNum { public static void main(String[] args) { Random random = new Random(); //随机数种子 Scanner sc = new Scanner(System.in); int toGuess = random.nextInt(100); while (true) { System.out.println("请输入数字: (1-100)"); int num = sc.nextInt(); if (num < toGuess) { System.out.println("低了低了格局低了"); } else if (num >

ToGuess) {System.out.println ("tall! really high!") ;} else {System.out.println ("you guessed it!") ; break;}} sc.close ();}} run the result

The above is how Java realizes the number guessing game. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Number version language right code more knowledge article result input run select practical preface that is work meeting article time see knowledge point Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Linux Redmi MariaDB macOS