猜测一个随机数与机会

Guessing a Random number with opportunities

本文关键字:一个 随机数 机会      更新时间:2023-09-26

所以我必须制作一个程序类游戏,是一个猜谜数字游戏,所以我制作了所有的程序,但我想告诉用户,你只有5次机会猜到这个数字,如果用户在5次机会中没有猜到,打印一条消息,说"JAJAJAJA再试一次",我不知道如何添加机会。有些东西是用西班牙语写的,因为我来自西班牙,所以这就是为什么。OHH该程序有一个菜单,第一个选项是指令,2是游戏,3是退出,我只是错过了向程序添加机会,就像用户有5岁的特定寿命一样。对不起我的语法chico的意思是小或更低,grande的意思是大

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class juego {
    public static void main(String[] args) throws IOException {
        proyecto obj = new proyecto();
        int w = (int) (5000 * Math.random() + 1);
        String x;
        int y;
        do {
            System.out.println("MENU");
            System.out.println("1.Instrucciones del juego");
            System.out.println("2. Juego");
            System.out.println("3. Salir");
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            y = Integer.parseInt(br.readLine());
            switch (y) {
            case 1:
                obj.instu();
                break;
            case 2:
                obj.proce(w);
                break;
            case 3:
                System.out.println("GRACIAS POR JUGAR");
                break;
            default:
                System.out.println("La opcion seleccionada no es valida");
            }
        } while (y != 3);
    }
}
class proyecto {
    void instu() {
        System.out.println("Instrucciones");
        System.out
                .println("El juego se trata de adivinar el numero, tendras 10 intentos para poder          adivinar");
        System.out.println("Crees que podras ganar?");
    }
    void proce(int w) throws IOException {
        int e;
        System.out.println("COMENCEMOS!!!!");
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        System.out.println("INSERTE EL NUMERO");
        {
            do {
                e = Integer.parseInt(br.readLine());
                if (e < w) {
                    System.out.println("EL numero insertado es CHICO");
                    System.out.println("Inserte un numero mas grande");
                } else {
                    System.out.println("EL numero  insertado es muy grande");
                }
                {
                    if (e == w) {
                        System.out.println("GANASTE");
                    }
                }
            } while (e != w);
        }
    }
}

(只给出提示-假设这是家庭作业,你肯定应该自己解决细节。)

目前你的循环结构是:

 do {
   ...
 } while (e != w);

所以你要循环直到玩家猜到答案。你需要循环,直到玩家猜到答案他们已经猜完了。

如果你想保持当前的循环结构,你可能想:

  • 保留一个变量(在循环外声明),其中包含迄今为止的猜测次数
  • 增加循环中的变量
  • 在循环终止条件下使用

或者,您可以将循环更改为for循环:

for (int guess = 0; guess < 5; guess++) {
  ...
}

如果玩家得到了正确的答案,就跳出循环。