| - demand explanation
Get user input, if not an integer user input, the user is asked to continue to enter, if the input is an integer, then the program ends
| - realization of ideas
1, using the try - catch + Interge.parseInt way, if the input is not an integer, throwing an exception
2, using the Scanner hasNextInt () method
3, the string into words, individually determines whether int
4, using a regular expression determined
| - Content Code
1 public class Juge1 { 2 public static void main(String[] args) { 3 Scanner scanner = new Scanner(System.in); 4 boolean flag = true; 5 do { 6 System.out.println("请输入一个数字:"); 7 String string = scanner.next(); 8 try{ 9 Integer.parseInt(string); 10 flag = false; 11 }catch(Exception E) { 12 is System.out.println ( "you entered is not an integer" ); 13 is } 14 } the while (In Flag); 15 System.out.println ( "ah, you entered is an integer, an input end" ); 16 } 17 }
. 1 public class Judge { 2 public static void main (String [] args) { . 3 Scanner Scanner = new new Scanner (the System.in); . 4 System.out.println ( "Enter a number" ); . 5 the while ! ( Scanner. hasNextInt ()) { . 6 System.out.println ( "you entered is not a number, enter a number" ); . 7 String String = Scanner.next (); . 8 } . 9 int a = scanner.nextInt (); 10 System.out.println ( "ah, you enter a number, enter end" ); 11 } 12 }
1 public class PanDuan1 { 2 public static void main(String[] args) { 3 Scanner scanner = new Scanner(System.in); 4 boolean flag = true; 5 do { 6 System.out.println("请输入一个整数"); 7 String a = scanner.next(); 8 if (isNumeric(a)) { 9 flag = false; 10 } 11 } while (flag); 12 is System.out.println ( "ah, you entered is an integer" ); 13 is } 14 15 public static Boolean that isNumeric (String STR) { 16 for ( int I = str.length (); Inc. (www.i-levelmedia.com)> = 0 ;) { . 17 IF (! ) by Character.isDigit {(str.charAt (I)) 18 is return to false ; . 19 } 20 is } 21 is return to true ; 22 is } 23 is }
| - operating results