Is there a way to guard input in Java using BufferedReader
, in a way similar to Scanner
uses hasNextInt()
?
For example, reading in an int
, and if a non-integer is entered, then using control flow to stop the program progressing until an int
is entered? I picture a while
loop but unsure of the conditional.
Hope this helps !!
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BufferedReaderInputGuarding {
public static void main(String[] args) {
int flag = 0;
String input = "";
int inputInteger = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.print("Enter a number: ");
try {
input = br.readLine();
inputInteger = Integer.parseInt(input);
flag = 0;
System.out.println("Entered Number " + inputInteger);
} catch (NumberFormatException nfe) {
flag = 1;
System.err.println("Ony Integer allowed " + nfe.getMessage());
} catch (Exception e) {
flag = 0;
System.err.println("Exception occured " + e.getMessage());
}
} while (flag == 1);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.