Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the game of guessing numbers by Java

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report