java - 提示用户猜测计算机随机选择的数字的 java 程序
问题描述
我是 Java 的初学者,我试图让这个程序在 1 到 1000 之间选择一个随机数并提示用户猜测这个数字,但程序似乎不起作用,我不知道它有什么问题.
package com.company;
import java.util.Scanner;
public class GradeBookTest {
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);
guess();
System.out.println("Guess a number between 1 and 1000.");
num = input.nextInt();
if (num >= 1 && num <= 1000)
{
while (checkNumber(num) != true)
{
System.out.println("Guess again");
num = input.nextInt();
checkNumber(num);
}
System.out.println("Congratulations. You " +
"guessed the number!");
}
}
public static int guess() {
return ( (int) (1 + Math.random()*1000) );
}
public static boolean checkNumber(int a){
int ans = guess();
if (a < ans)
{
System.out.println("low");
return false;
}
else if (a > ans)
{
System.out.println("high");
return false;
}
else
return true;
}
}
解决方案
尝试这个
public class Guess {
public static void main (String [] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Generates the Random Number
int randomNumber = (int)(Math.random() * 1000);
System.out.print("Guess a number between 1 and 1000: ");
// Get user guess
int guess = input.nextInt();
while (guess != randomNumber) {
// Informs the user whether his guess is high or low
if (guess > randomNumber) {
System.out.println("Your guess is high");
} else {
System.out.println("Your guess is low");
}
// Asks the user for another guess
System.out.print("Make another guess : ");
guess = input.nextInt();
}
System.out.println("Congratulations ! You guessed the number");
}
}
推荐阅读
- mongodb - 在 Web 服务分页中使用 DB 游标(生成继续令牌)
- c# - 从源生成器内部读取属性属性
- itfoxtec-identity-saml2 - /idp/ 端点来自哪里?
- java - 如何使用applescript从chromedriver实例关闭上传对话框窗口?
- reactjs - 如何去除 Material-UI 对话框中的阴影?
- google-cloud-build - 仅当命令由拉取请求触发时如何执行命令?
- macos - Clang 链接器“找不到 -lCocoa 的库”
- python-3.x - Django - PermissionRequiredMixin - 在当前视图中返回“permission_denied_message”,而不是 403 页面?
- sql - 何时将数据物理化到表中与保留在 redshift 中的视图中?
- azure - Aks 错误 无法耗尽节点,中止缩减