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.*; 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 } 051 else if (g == -1) { 052 hint = "a number next time"; 053 } 054 else if (g < answer) { 055 hint = "higher"; 056 } 057 else if (g > answer) { 058 hint = "lower"; 059 } 060 } 061 062 public boolean getSuccess() { 063 return success; 064 } 065 066 public String getHint() { 067 return "" + hint; 068 } 069 070 public int getNumGuesses() { 071 return numGuesses; 072 } 073 074 public void reset() { 075 answer = Math.abs(new Random().nextInt() % 100) + 1; 076 success = false; 077 numGuesses = 0; 078 } 079 }