views:

185

answers:

5

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.println("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);
}
+2  A: 

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.

Etaoin
A: 
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");
}
Dave
Doesn't handle the `NumberFormatException` -- and also, this being (I suspect) a homework problem, let's maybe prefer good hints over explicitly writing out the solution.
Etaoin
A: 

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.

suihock
A: 

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.

Michael Aaron Safyan
A: 

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);

}

}

flopex