如何在Java中检查输入是否为整数?
在我的程序中,我想要用户输入整数。 我想要在用户输入非整数值时显示错误消息。 我怎样才能做到这一点。 我的程序是找到圈子的区域。 在哪个用户将输入radius的值。 但是如果用户输入一个字符,我想要显示一条消息,说明输入无效。
这是我的代码:
int radius, area; Scanner input=new Scanner(System.in); System.out.println("Enter the radius:\t"); radius=input.nextInt(); area=3.14*radius*radius; System.out.println("Area of circle:\t"+area);
如果您使用Scanner
获得用户输入,则可以执行以下操作:
if(yourScanner.hasNextInt()) { yourNumber = yourScanner.nextInt(); }
如果不是,则必须将其转换为int
并捕获NumberFormatException
:
try{ yourNumber = Integer.parseInt(yourInput); }catch (NumberFormatException ex) { //handle exception here }
如果用户输入是String
那么您可以尝试使用parseInt
方法将其解析为整数,当输入不是有效数字字符串时抛出NumberFormatException
:
try { int intValue = Integer.parseInt(stringUserInput)); }(NumberFormatException e) { System.out.println("Input is not a valid integer"); }
你可以试试这种方式
String input = ""; try { int x = Integer.parseInt(input); // You can use this method to convert String to int, But if input //is not an int value then this will throws NumberFormatException. System.out.println("Valid input"); }catch(NumberFormatException e) { System.out.println("input is not an int value"); // Here catch NumberFormatException // So input is not a int. }
String input = ""; int inputInteger = 0; BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); System.out.println("Enter the radious: "); try { input = br.readLine(); inputInteger = Integer.parseInt(input); } catch (NumberFormatException e) { System.out.println("Please Enter An Integer"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } float area = (float) (3.14*inputInteger*inputInteger); System.out.println("Area = "+area);
使用Integer.parseIn(String),可以将字符串值解析为整数。 如果输入字符串不是正确的数字,你还需要捕获exception。
int x = 0; try { x = Integer.parseInt("100"); // Parse string into number } catch (NumberFormatException e) { e.printStackTrace(); }
您可以使用try-catch块来检查整数值
例如:
用户以字符串forms输入
try { int num=Integer.parseInt("Some String Input"); } catch(NumberFormatException e) { //If number is not integer,you wil get exception and exception message will be printed System.out.println(e.getMessage()); }