-3

所以我只是在学习java,我知道这个问题很愚蠢,这是来自Head Frist Java一书。当我尝试输入字母而不是数字时,它会崩溃,我该如何解决?如果我想让它在输入字母时说“请用数字再试一次”。

    public class Game {
    public static void main(String[] args)
{
    int numOfGuesses = 0;
    GameHelper helper = new GameHelper();

    SimpleDotCom theDotCom = new SimpleDotCom();
    int randomNum = (int) (Math.random() * 5);

    int[] locations = {randomNum, randomNum+1, randomNum+2};
    theDotCom.setLocationCells(locations);
    boolean isAlive = true;
    while (isAlive == true)
    {
        String guess = helper.getUserInput("enter a number");
        String result = theDotCom.checkYourself(guess);
        numOfGuesses++;
        if (result.equals("kill")) {
            isAlive = false;
            System.out.println("You took " + numOfGuesses + " guesses");
        }
    }
}

}

    public class GameHelper {

    private static final String alphabet = "abcdefg";
    private int gridLength = 7;
    private int gridSize = 49;
    private int [] grid = new int[gridSize];
    private int comCount = 0;


    public String getUserInput(String prompt) {
    String inputLine = null;
    System.out.print(prompt + "  ");
    try {
    BufferedReader is = new BufferedReader(
 new InputStreamReader(System.in));
   inputLine = is.readLine();
   if (inputLine.length() == 0 )  return null; 
 } catch (IOException e) {
   System.out.println("IOException: " + e);
 }
 return inputLine.toLowerCase();

}

public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;

public void setLocationCells(int[] locs)
{
    locationCells = locs;
}

public String checkYourself(String stringGuess) {
    int guess = Integer.parseInt(stringGuess);
    String result = "miss";
    for (int cell: locationCells)
    {
        if (guess == cell) {
            result = "hit";
            numOfHits++;
            break;
        }
    }
    if (numOfHits == locationCells.length)
    {
        result = "kill";
    }
    System.out.println(result);
    return result;
}
4

3 回答 3

2

在下面的 -

int guess = Integer.parseInt(stringGuess);

只有stringGuess包含某个整数(在 [-2147483648 - 2147483647] 范围内)时,解析才会成功。否则,它会失败并出现异常。

为避免这种情况,您必须确保stringGuess包含正确的值。

以下是价值的来源 -

String guess = helper.getUserInput("enter a number");
String result = theDotCom.checkYourself(guess);

方法是getUserInput()——

public String getUserInput(String prompt) {
    String inputLine = null;
    System.out.print(prompt + "  ");
    try {
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        inputLine = is.readLine();
        if (inputLine.length() == 0)
            return null; // this cannot be parsed
    } catch (IOException e) {
        System.out.println("IOException: " + e);
    }
    return inputLine.toLowerCase(); //this might not be an integer
}

这就是您需要修复的部分。

以下应该做的工作 -

//...
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
while (true) { //keep reading
    try {
        inputLine = is.readLine();
        int num = Integer.parseInt(inputLine); //make sure it's an integer
        if(num > -1 && num < 10) { // if it is, and within [0-9]
            break; // stop reading
        }
    } catch (Exception e) { // if not prompt again
        System.out.println("pleasse try again with a number within [0-9]");
    }
}
return inputLine; // no to lower case, it's a number

你仍然可以改进它,比如只返回一个int表单这个方法,而不是String.

于 2013-06-14T04:41:11.970 回答
0

如果您不知道 stringGuess 是否为整数,则可以放入Integer.parseInt(stringGuess)一个try { } catch构造。parseInt如果其输入不能转换为整数,则抛出异常,因此捕获它。在 catch 块中,我们知道它不是整数。否则它是一个整数。现在做你想做的逻辑(显示一条消息,选择循环或不循环等)

(如果你还没有做过异常处理,请查阅 Java 中的 try 和 catch)

于 2013-06-14T04:28:39.357 回答
0

正如@patashu 所建议的,如果不是数字(字符串形式的数字try{ } catch() { }
),您可以将 其用作Integer.parseInt(argument)throws 。 如果用户输入字母,则再次调用您的输入函数,那么您可以通过在块内调用该特定输入方法来简单地做到这一点,例如:NumberFormatExceptionargument
catch


try{
    int guess = Integer.parseInt(stringGuess);
    -----
    -----
}
catch(NumberFormatException e){
     System.out.println("Oooppps letter entered - try again with number ");
     /**
     now here make call to your method that takes input i.e getUserInput() in your case 
    **/
}
于 2013-06-14T04:38:03.403 回答