嗨,我目前在猜测游戏代码时遇到异常。我想为字符串输入(而不是int)添加异常,并且还要输入超出限制(50)的数字的例外。感谢。
public static void main (String[] args)
{
Random ran = new Random();
int numberToGuess = ran.nextInt(50)+1;
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess;
boolean win = false;
while (win == false)
{
System.out.println("Guess a number from 1 to 50!");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess)
{
win = true;
}
else if (guess < numberToGuess)
{
System.out.println("Too low. Try again.");
}
else if (guess > numberToGuess)
{
System.out.println("Too high. Try again.");
}
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
答案 0 :(得分:0)
这是一个潜在的解决方案:
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
import java.util.Scanner;
public class StackOverflow45419907 {
private final Scanner input;
final int numberToGuess;
public StackOverflow45419907() {
this.input = new Scanner(System.in);
numberToGuess = new Random().nextInt(50) + 1;
}
public static void main(String[] args) {
new StackOverflow45419907().playGame();
}
private void playGame() {
int numberOfTries = 0;
int guess = -1;
while (guess != numberToGuess) {
guess = collectGuess();
numberOfTries++;
printClue(guess);
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
private void printClue(int guess) {
if (guess < numberToGuess) {
System.out.println("Too low. Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high. Try again.");
}
}
private int collectGuess() {
System.out.println("Guess a number from 1 to 50!");
final String potentialGuess = input.nextLine();
return validateAndParse(potentialGuess);
}
private int validateAndParse(String potentialGuess) {
if (!StringUtils.isNumeric(potentialGuess)) {
throw new IllegalArgumentException("not numeric: " + potentialGuess);
}
final int asInt = Integer.parseInt(potentialGuess);
if (asInt > 50 || asInt < 1) {
throw new IllegalArgumentException("value out of valid range: " + asInt);
}
return asInt;
}
}
答案 1 :(得分:-1)
我真的认为你不需要抛出异常。您可以使用
Scanner#hasNextInt()
验证输入是否为整数。然后将它分配给猜测变量,然后检查它是否大于50。
如果你真的要抛出异常。使用
throw new RuntimeException(message)
如果输入不是整数或大于50。
修改强> 我不会那样使用它,但我相信你只想了解异常。
System.out.println("Guess a number from 1 to 50!");
numberOfTries++;
if (!input.hasNextInt())
throw new IllegalArgumentException("Input must be a number");
guess = input.nextInt();
if (guess < 1 || guess > 50)
throw new IllegalArgumentException("Input must be a number from 1 to 50");