开发者

How can I take only integer input from keyboard and if input is invalid how do I ask user again?

This is what I have written so far but when exception is raised it does not again ask the user for input.

    do {
        System.out.print开发者_运维百科ln("Enter the number of stones to play with: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
        String temp = br.readLine();
        key = Integer.parseInt(temp);
    } while (key < 0 && key > 9);

    if (key < 0 || key > 10)
        throw new InvalidStartingStonesException(key);

    player1 = new KeyBoardPlayer();
    player2 = new KeyBoardPlayer(); 
    this.player1 = player1;
    this.player2 = player2;
    state = new KalaGameState(key);
} catch (NumberFormatException nFE) {
    System.out.println("Not an Integer");
} catch (IOException e) {
    System.out.println(e);
}


As soon as that NumberFormatException is thrown, you jump out of the loop and down to the catch. If your try-catch block is inside your while loop, it'll have the effect you're looking for. You may need to adjust the condition on the loop.


An alternative way is to check if the string input matches a regular expression for an integer. If it doesn't match, you ask for the input again.


See Teleteype.readInt() from the Java Project Template. The basics of it is that you read input as a String, and then you convert it to an integer using Integer.parseInt(), which will throw NumberFormatException if the contents of the String is not an integer, which you can handle by catching the NumberFormatException.


What I would recommend is instead of using all these exceptions is to make separate methods that read specific data types. (Ex.)

import java.util.Scanner;

public class HelloWorld {

public static void main(String[] args){
    int n = getInteger("Enter integer: ");

    System.out.println(n);

}

public static boolean isInteger(String s){

    if(s.isEmpty())return false;
    for (int i = 0; i <s.length();++i){
        char c = s.charAt(i);
        if(!Character.isDigit(c) && c !='-')
            return false;
    }

    return true;
}

public static int getInteger(String prompt){
    Scanner input = new Scanner(System.in);
    String in = "";
    System.out.println(prompt);
    in = input.nextLine();
    while(!isInteger(in)){
        System.out.println(prompt);
        in = input.nextLine();
    }

    return Integer.parseInt(in);

}

}


while (true) {
   System.out.println("Enter the number of stones to play with: ");
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
   key = Integer.parseInt(br.readLine());
   if (key > -1 && key < 10)
      break;
   else
      System.out.println("Invalid number of stones. Choose from 0 - 9");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜