猜数字JAVA
很高兴为您提供猜数字的JAVA代码,具体如下:
import java.util.Scanner;
public class GuessNumber { public static void main(String[] args) { int number = (int) (Math.random() * 100) + 1; int guess = 0; int count = 0; Scanner input = new Scanner(System.in); System.out.println("猜数字游戏开始了,请输入你猜的数字:"); while (guess != number) { guess = input.nextInt(); count++; if (guess > number) { System.out.println("猜大了,请重新输入:"); } else if (guess < number) { System.out.println("猜小了,请重新输入:"); } else { System.out.println("恭喜你猜对了,你一共猜了" + count + "次。"); } } } }
在这个程序中,我们使用了Math.random()函数来生成一个1到100之间的随机整数,然后使用Scanner类来读取用户输入的数字,并使用while循环来不断询问用户是否猜对了数字。如果用户猜大了,我们会提示用户重新输入;如果用户猜小了,我们同样提示用户重新输入。如果用户猜对了,我们会输出恭喜语句,并告诉用户一共猜了多少次。
原文地址: https://www.cveoy.top/t/topic/twq 著作权归作者所有。请勿转载和采集!