jogo de adivinhação 0-100 java

Robert Nelson:

Eu tenho um código que precisa conjunto de 0-100 e tê-lo ser uma possibilidade para ter zero ser a resposta certa. Pus o meu ints final para MAX (100) / MIN (0). Mas 0 nunca é a resposta certa. Eu sou 4 anos em codificação com 2 anos de experiência em Java, mas parece que qualquer problema 1-100 ou 1- qualquer outro MAX é bom. Por favor, ajuda, ou explicar se 0 não é uma seleção permitido.

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        Random generator = new Random();

        int MIN = 0;
        int MAX = 100;
        int answer;
        int guess;
        String another = "y";
        boolean flag = false;
        boolean anotherFlag = true;

        while(anotherFlag){
            answer = generator.nextInt(MAX) + 1;

            System.out.println("I'm thinkin of a number between 0 and " + MAX );
            System.out.println("Can you guess what it is? \n");
            flag = false;
            while(!flag) {
                guess = scan.nextInt();

                if(guess == answer){
                    System.out.println("You guessed correctly");
                    flag = true;

                } else{
                    System.out.println("That was wrong, try again.");
                }
            }

            System.out.println("Want to Play again?(y/n)");
            another = scan.next();

            if(another.equalsIgnoreCase("y") == true){
                anotherFlag = true;
            } else{
                anotherFlag = false;
            }
        }

Obrigado pela ajuda.

Trivedin:

Parece que o problema é com

    answer = generator.nextInt(MAX) + 1;

Sua faixa de resposta é 1 - MAX.

se você deseja gerar um número aleatório entre 0 - MAX, onde MAX = 100. Você deve contra gravação

    answer = generator.nextInt(MAX+1);

Porque, como por API Java (java v8),

    public int nextInt(int bound)

retorna um pseudo-aleatório, int valor distribuído uniformemente entre 0 (inclusive) e o valor especificado (exclusive)

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=211442&siteId=1
Recomendado
Clasificación