View Javadoc

1   /*
2   * Licensed to the Apache Software Foundation (ASF) under one or more
3   * contributor license agreements.  See the NOTICE file distributed with
4   * this work for additional information regarding copyright ownership.
5   * The ASF licenses this file to You under the Apache License, Version 2.0
6   * (the "License"); you may not use this file except in compliance with
7   * the License.  You may obtain a copy of the License at
8   *
9   *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17  
18  /*
19   * Originally written by Jason Hunter, http://www.servlets.com.
20   */
21  
22  package num;
23  
24  import java.util.Random;
25  
26  public class NumberGuessBean {
27  
28      int answer;
29      boolean success;
30      String hint;
31      int numGuesses;
32  
33      public NumberGuessBean() {
34          reset();
35      }
36  
37      public void setGuess(String guess) {
38          numGuesses++;
39  
40          int g;
41          try {
42              g = Integer.parseInt(guess);
43          }
44          catch (NumberFormatException e) {
45              g = -1;
46          }
47  
48          if (g == answer) {
49              success = true;
50          } else if (g == -1) {
51              hint = "a number next time";
52          } else if (g < answer) {
53              hint = "higher";
54          } else if (g > answer) {
55              hint = "lower";
56          }
57      }
58  
59      public boolean getSuccess() {
60          return success;
61      }
62  
63      public String getHint() {
64          return "" + hint;
65      }
66  
67      public int getNumGuesses() {
68          return numGuesses;
69      }
70  
71      public void reset() {
72          answer = Math.abs(new Random().nextInt() % 100) + 1;
73          success = false;
74          numGuesses = 0;
75      }
76  }