English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

in java, how do i make sure a user entry is an int using a while loop?

2006-12-08 11:39:43 · 2 answers · asked by BEEFSHIELD 3 in Computers & Internet Programming & Design

2 answers

If the value is in a string, just place this in a try statement and catch a NumberFormatException

Integer.parseInt(stringValue)

2006-12-08 11:43:20 · answer #1 · answered by nuprn1 2 · 0 0

Using exception handling for normal processing is very inefficient, as well as being counter to the purpose of exceptions. An approach that meets your requirement to use a while loop is to use a combination of String class and Char class methods.

Use the String class's toCharArray() method to get the string as an array of chars. Then loop through the array, checking each char using the Character class's isDigit() method. Note that you may need to do some more checking if you indeed need to guarantee that the value is an int, not just an integer number.

2006-12-09 03:08:43 · answer #2 · answered by vincentgl 5 · 0 0

fedest.com, questions and answers