我想到用c++能编出一个猜数字游戏,于是我就尝试用java编写一个
代码如下:
import java.util.Scanner; import java.util.Random; public class GuessTheNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); int min = 1; int max = 100; int randomNumber = random.nextInt(max - min + 1) + min; int guess; int attempts = 0; System.out.println("欢迎来到猜数字游戏!"); System.out.println("我已经选好了一个数字,范围在 " + min + " 到 " + max + " 之间。"); do { System.out.print("请输入你的猜测:"); guess = scanner.nextInt(); attempts++; if (guess < randomNumber) { System.out.println("猜的数字太小了!"); } else if (guess > randomNumber) { System.out.println("猜的数字太大了!"); } else { System.out.println("恭喜你,猜对了!"); System.out.println("你一共猜了 " + attempts + " 次。"); } } while (guess != randomNumber); scanner.close(); } }
本代码用的是do {} while()的循环