我正在尝试为我已编写的程序添加例外。当用户试图欺骗数字猜测程序以获取更高和更低的方法以及在游戏中添加try / catch以显示错误时,我需要编写异常。我几乎把它写得正确但是在最后可能的结果之前抛出了异常。附件是我写的类文件以及运行游戏的程序。
这是我的数字猜测逻辑
的类public class NumberGuesser {
private int min, max, midpoint, origMin, origMax;
public NumberGuesser()
{
min = 1;
max = 100;
}
public NumberGuesser(int lowerBound, int upperBound)
{
min = lowerBound;
max = upperBound;
origMin = lowerBound;
origMax = upperBound;
}
public void setMin(int value)
{
min = value;
}
public void setMax(int value)
{
max = value;
}
public int getMin()
{
return min;
}
public int getMax()
{
return max;
}
public void higher()
{
min = getCurrentGuess() + 1;
if (min == max)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public void lower()
{
max = getCurrentGuess() -1;
if (max == min)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public int getCurrentGuess()
{
midpoint = (max + min) /2;
return midpoint;
}
public void reset()
{
min = origMin;
max = origMax;
}
}
这是运行游戏的程序。
import java.util.*;
public class GuessingProgram {
public static void main(String[] args) {
do
{
playOneGame();
}
while (shouldPlayAgain());
}
public static void playOneGame()
{
char input = 0;
Scanner keyboard = new Scanner(System.in);
NumberGuesser game = new NumberGuesser(1,100);
System.out.println("NUMBER GUESSER GAME");
System.out.println("-------------------");
System.out.println("Think of a number between 1 and 100");
while (input != 'c')
{
try
{
System.out.print("Is your number " + game.getCurrentGuess() + "?" +
" (h/l/c): ");
input = keyboard.next().charAt(0);
if (input == 'h' || input == 'H')
game.higher();
else if (input == 'l' || input == 'L')
game.lower();
else if (input == 'c' || input == 'C')
game.reset();
}
catch(IllegalStateException e)
{
System.out.println("Invalid input, You are cheating!!!");
}
}
}
public static boolean shouldPlayAgain()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Great! Do you want to play again? (y/n): ");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("y"))
return true;
else
return false;
}
}
这是我的输出和它应该猜测的数字是77
想想1到100之间的数字 你的号码是50吗? (h / l / c):h
你的号码是75吗? (h / l / c):h
你的号码是88吗? (h / l / c):l
你的号码是81吗? (h / l / c):l
你的号码是78吗? (h / l / c):l
你的号码是76吗? (h / l / c):h
输入无效,你在作弊!!!
你的号码是77吗? (h / l / c):
答案 0 :(得分:2)
如果min
和max
达到相同的值,则表示您找到了正确的值。如果您在找到正确的值后,如果您说数字更高/更低,我认为您想要illegalStateException
,max < min
。