Devinez un programme numérique avec Java


J'essaie de créer un programme en Java dans lequel l'ordinateur devine aléatoirement un nombre entre 1 et 100 et permet à l'utilisateur de deviner le nombre.

Si le nombre est inférieur au nombre aléatoire le programme devrait dire: lower! et s'il est supérieur, le programme devrait dire: higher!

Si l'utilisateur devine le bon nombre, il devrait dire congratulations you guessed the right number in X amount of tries.

C'est ce que j'ai jusqu'à présent, toute aide serait appréciée!

import java.util.Scanner;

public class QuestionOne
{
  public static void main(String args[])
  {
   Scanner keyboard = new Scanner(System.in);

   int a = 1 + (int) (Math.random() * 99);
   int guess;

   System.out.println("I am thinking of a number from 1 to 100 ... guess what it is ?");
   guess = keyboard.nextInt();

   while(guess != a){
   if (guess > a)
   {  
     System.out.println("lower!");

   }
   else if (guess < a) 
   {
    System.out.println("higher!");

   }
   else 
   {
     System.out.println("Congratulations.   You guessed the number with X tries!");
   }
   }
  }
}
Author: K48, 2014-01-10

6 answers

Vous n'obteniez pas d'autre entrée ou ne gardiez pas de compte. Essayez ceci

public static void main(String args[]) {
    Scanner keyboard = new Scanner(System.in);
    int count = 0;
    int a = 1 + (int) (Math.random() * 99);
    int guess = 0;

    System.out.println("I am thinking of a number from 1 to 100"
        + " ... guess what it is ?");

    while (guess != a) {
        guess = keyboard.nextInt();
        count++;
        if (guess > a) {
            System.out.println("lower!");
        } else if (guess < a) {
            System.out.println("higher!");
        }
    }
    System.out.println("Congratulations. You guessed the number with "
        + count + " tries!");
}

Sortie

I am thinking of a number from 1 to 100 ... guess what it is ? 
50
higher!
75
lower!
62
Congratulations.   You guessed the number with 3 tries!
 1
Author: Elliott Frisch, 2014-01-10 16:46:13

Vous avez oublié d'obtenir un nouvel int du scanner dans chaque boucle:)

import java.util.Scanner;

public class QuestionOne
{
  public static void main(String args[])
  {
   Scanner keyboard = new Scanner(System.in);

   int a = 1 + (int) (Math.random() * 99),
       guess, 
       count = 0;

   System.out.println("I am thinking of a number from 1 to 100 ... guess what it is ?");

   while((guess = keyboard.nextInt()) != a){
     if (guess > a)
     {  
       System.out.println("lower!");
     }
     else
     {
       System.out.println("higher!");
     }
     count++;
   }

   System.out.println("Congratulations.   You guessed the number with "+ count +" tries!");
  }

}

Edit: Je m'ennuie actuellement... Ajouter le compteur ;)

 3
Author: NiziL, 2014-01-10 16:20:11

Vous devez déplacer la partie félicitations hors de la boucle while. Si vous devinez le nombre correct, il n'entrera pas dans la boucle et n'affichera donc jamais cette déclaration. Ce serait plus évident si vous corrigiez vos indentations. Sa mauvaise forme pour avoir tout au même niveau d'indentation.

 0
Author: BobbyD17, 2014-01-10 16:09:40

Eh bien, j'ai traversé ce sujet et j'aimerais partager le code que j'ai compris aussi car c'était une question amusante.Cela peut même être utilisé comme un jeu simple.voici le code psuedocode pour cela: D

do{
        number=(int)(Math.random()*100);

   }while(number<10);
do
    {
  lottery=Integer.parseInt(JOptionPane.showInputDialog(null,"guess the two digit number which is in my mind!!!! \nenter the number"));
  if(number<lottery)
  {
      JOptionPane.showMessageDialog(null,"guess a more lower number");
      count ++;
   }
  else if(number>lottery)
  {
      JOptionPane.showMessageDialog(null,"guess a more higher number");
      count ++;
     }
  else
      JOptionPane.showMessageDialog(null,"you have guessed the correct number "+number+" in"+count+" tries");
    }while(lottery!=number);</i>
 0
Author: The_Fresher, 2014-05-15 19:36:39

Essayez ceci, j'espère que cela vous aidera.

public class BinarySearch

{ static Scanner sc = new Scanner(System.in);

public static void main(String a[]) {
    int count = 100;
    BinarySearch bs = new BinarySearch();
    int[] inputArr = bs.takeInputsInCount(count);
    System.out
            .println("For every question, press Enter if answer is YES, else you can press any other key");
    System.out
            .println("Think of a number between 1 to 100, press Enter to continue");
    String input = sc.nextLine();
    if (input.isEmpty()) {
        int element = bs.getElementByBinarySearch(inputArr, count);
        System.out.println("Your number is : " + element);
    } else {
        System.out.println("exiting... ");

    }
}

private int getElementByBinarySearch(int[] arr, int len) {
    int first = 0;
    int last = len - 1;
    if (isEqual(arr[first]))
        return arr[first];
    if (isEqual(arr[last]))
        return arr[last];
    while (last > first) {
        int middle = (first + last) / 2;

        if (isEqual(arr[middle]))
            return arr[middle];
        if (isGreater(arr[middle])) {
            first = middle + 1;
            if (isEqual(arr[first]))
                return arr[first];
        } else {
            last = middle - 1;
            if (isEqual(arr[last]))
                return arr[last];
        }

    }

    return 0;
}

private boolean isEqual(int m) {
    Boolean equalFlag = false;

    System.out.println("Is your number :" + m + " ?");
    String input = sc.nextLine();
    if (input.isEmpty()) {
        equalFlag = true;
    }
    return equalFlag;

}

private boolean isGreater(int m) {
    Boolean equalFlag = false;

    System.out.println("Is your number greater than :" + m + " ? ");
    String input = sc.nextLine();
    if (input.isEmpty()) {
        equalFlag = true;
    }
    return equalFlag;

}

private int[] takeInputsInCount(int count) {
    int length = count;
    int tempArray[] = new int[length];
    for (int i = 0; i < length; i++) {
        try {
            tempArray[i] = i + 1;
        } catch (Exception e) {
            break;
        }
    }

    return tempArray;
}}
 0
Author: akshay, 2018-07-26 13:36:19
import java.util.Random;

public static void main(String[] args)
{

    int a = 1 + (int)(Math.random()*99);
    int guess = 0;
    int count = 0;

    while(guess != a)
    {
        guess = Integer.parseInt(JOptionPane.showInputDialog("Enter a Number"));
        count++;
        if (guess > a)
        {
         JOptionPane.showMessageDialog(null,"lower!");
        }
       else if (guess < a)
        {
         JOptionPane.showMessageDialog(null,"higher!");
        }
    }
         JOptionPane.showMessageDialog(null,"Congratulations. You guessed the number with " +count+ " tries");
    }

}

 -1
Author: Sandali Dinalaththa, 2015-07-11 14:01:48