001    /*
002    * Licensed to the Apache Software Foundation (ASF) under one or more
003    * contributor license agreements.  See the NOTICE file distributed with
004    * this work for additional information regarding copyright ownership.
005    * The ASF licenses this file to You under the Apache License, Version 2.0
006    * (the "License"); you may not use this file except in compliance with
007    * the License.  You may obtain a copy of the License at
008    *
009    *     http://www.apache.org/licenses/LICENSE-2.0
010    *
011    * Unless required by applicable law or agreed to in writing, software
012    * distributed under the License is distributed on an "AS IS" BASIS,
013    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014    * See the License for the specific language governing permissions and
015    * limitations under the License.
016    */
017    
018    /*
019     * Originally written by Jason Hunter, http://www.servlets.com.
020     */
021    
022    package num;
023    
024    import java.util.Random;
025    
026    public class NumberGuessBean {
027    
028        int answer;
029        boolean success;
030        String hint;
031        int numGuesses;
032    
033        public NumberGuessBean() {
034            reset();
035        }
036    
037        public void setGuess(String guess) {
038            numGuesses++;
039    
040            int g;
041            try {
042                g = Integer.parseInt(guess);
043            }
044            catch (NumberFormatException e) {
045                g = -1;
046            }
047    
048            if (g == answer) {
049                success = true;
050            } else if (g == -1) {
051                hint = "a number next time";
052            } else if (g < answer) {
053                hint = "higher";
054            } else if (g > answer) {
055                hint = "lower";
056            }
057        }
058    
059        public boolean getSuccess() {
060            return success;
061        }
062    
063        public String getHint() {
064            return "" + hint;
065        }
066    
067        public int getNumGuesses() {
068            return numGuesses;
069        }
070    
071        public void reset() {
072            answer = Math.abs(new Random().nextInt() % 100) + 1;
073            success = false;
074            numGuesses = 0;
075        }
076    }