用Java猜数字程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21048870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:11:21  来源:igfitidea点击:

Guess a number program with Java

javaloopsif-statementwhile-loop

提问by user3182418

I am trying to create a program in Java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number.

我正在尝试用 Java 创建一个程序,其中计算机随机猜测 1-100 之间的数字,并允许用户猜测该数字。

If the number is lower than the random number the program should say: lower!and if higher, the program should say: higher!

如果数字小于随机数,程序应该说:lower!如果更高,程序应该说:higher!

If the user guesses the right number, it should say congratulations you guessed the right number in X amount of tries.

如果用户猜对了数字,它应该说congratulations you guessed the right number in X amount of tries

This is what I have so far, any help would be appreciated!

到目前为止,这是我所拥有的,任何帮助将不胜感激!

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!");
   }
   }
  }
}

采纳答案by Elliott Frisch

You weren't getting another input, or keeping count. Try this

你没有得到另一个输入,或保持计数。尝试这个

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!");
}

Output

输出

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!

回答by NiziL

You forgot to get a new int from the scanner in each loop :)

您忘记在每个循环中从扫描仪获取新的 int :)

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 :I'm currently bored... Add the counter ;)

编辑:我现在很无聊……添加计数器;)

回答by BobbyD17

You need to move the congratulations part out of the while loop. If you guess the correct number, it will not go into the loop and therefore will not ever display that statement. This would be more obvious if you fixed your indentations. Its bad form to have everything at the same indentation level.

您需要将祝贺部分移出 while 循环。如果您猜对了数字,它将不会进入循环,因此永远不会显示该语句。如果您修复了缩进,这将更加明显。将所有内容都置于同一缩进级别是一种糟糕的形式。

回答by The_Fresher

Well I crossed across this topic and would like to share the code I figured out too since it was a fun question.This can even be used as a simple game.below is the psuedocode for it :D

好吧,我跨越了这个话题,想分享我也想出的代码,因为这是一个有趣的问题。这甚至可以用作一个简单的游戏。下面是它的伪代码: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>

回答by Sandali Dinalaththa

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");
    }

}

}

回答by akshay

Try this, hope it will help.

试试这个,希望它会有所帮助。

public class BinarySearch

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;
}}