gpt4 book ai didi

java - 猜数字游戏每次猜测都会生成不同的数字

转载 作者:行者123 更新时间:2023-11-30 04:24:52 26 4
gpt4 key购买 nike

我有一个 Java 服务器页面,允许用户从 1-1000 中选择一个数字。然后,该页面使用输入的号码并查明该号码是否与生成的号码匹配。 --如果^不清楚的话请看下面的图片。目前,每次用户猜测一个数字时,无论正确与否,程序都会生成一个不同的数字。如何使程序仅在用户刷新页面或猜测正确时生成数字?

JSP代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import = "Chapter12.RandomGuess" %>
<jsp:useBean id = "randomGuessId" class = "Chapter12.RandomGuess" scope = "page" >
</jsp:useBean>
<jsp:setProperty name = "randomGuessId" property = "*" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guess Random Number</title>
</head>
<body>
<h3>Guess a number from 1 to 1000</h3>
<form method = "post">
Enter guess: <input name = "guess" /><br /><br />
<input type = "submit" name = "Submit" value = "Take Guess" />
<input type = "reset" value = "Reset" /><br /><br />
Your guess of <jsp:getProperty name = "randomGuessId" property="guess" />
is <%= RandomGuess.guess(randomGuessId.getAnswer()) %>
</form>
</body>
</html>

Java 代码:

import java.util.Random;

public class RandomGuess {
private int guess;
Random r = new Random();
private int low = 1;
private int high = 1000;
int R = r.nextInt(high-low) + low;

public int getGuess() {
return guess;
}

public void setGuess(int newValue) {
guess = newValue;
}

public String getAnswer() {
String tooLow = "too low.";
String tooHigh = "too high.";
String correct = "correct!";
if(guess == R)
return correct;
else if(guess < R)
return tooLow;
else
return tooHigh;
}
public static String guess(String s) {
return s;
}
}

图片:http://i.imgur.com/dMSZ7SD.png

最佳答案

每次页面刷新时,都会创建一个新的 Bean 实例 - 并带有一个新编号。

要在调用之间保留号码,请在类中使用静态字段。

<小时/>

更好的是,使用 JavaScript!

关于java - 猜数字游戏每次猜测都会生成不同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com