如何修复我的代码以便输入字母

时间:2013-06-14 04:24:41

标签: java

所以我只是学习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;
}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

(如果你还没有进行异常处理,请查看try和catch in Java)

答案 2 :(得分:0)

根据@patashu的建议,您可以使用try{ } catch() { }
如果Integer.parseInt(argument)不是数字(以字符串的形式编号),则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 **/ } 块内调用特定的输入方法来完成它,如:


{{1}}