View Javadoc

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