用Java猜数字程序 [英] Guess a number program with Java

查看:94
本文介绍了用Java猜数字程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如果数字小于随机数,则程序应显示:lower!;如果数字大于随机数,则程序应显示:higher!

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

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

If the user guesses the right number, it should say 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!");
   }
   }
  }
}

推荐答案

您没有得到其他输入,也没有保持计数.试试这个

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

输出

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!

这篇关于用Java猜数字程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆