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