如何使用Scanner检查用户输入是否为整数? [英] How to check the user input is an integer or not with Scanner?

查看:146
本文介绍了如何使用Scanner检查用户输入是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望国家/地区代码是用户输入的整数.我希望在用户输入非整数的代码时显示错误消息.我怎样才能做到这一点?该程序是要求用户输入国家名称和国家/地区代码.用户将在其中输入国家/地区代码.但是,如果用户输入一个字符,我希望显示一条消息,说输入无效".

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.

System.out.println("Enter country name:");                     
countryName = in.nextLine();
System.out.println("Enter country code:");            
int codeNumber = in.nextInt(); 
in.nextLine();

推荐答案

如果输入的不是int值,则ScannernextInt()(请参阅

If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:

  Scanner in = new Scanner(System.in);
  boolean isNumeric = false;//This will be set to true when numeric val entered
  while(!isNumeric)
     try {
        System.out.println("Enter country code:");
        int codeNumber = in.nextInt(); 
        in.nextLine();
        isNumeric = true;//numeric value entered, so break the while loop
        System.out.println("codeNumber ::"+codeNumber);
  } catch(InputMismatchException ime) {
     //Display Error message
     System.out.println("Invalid character found,
            Please enter numeric values only !!");
     in.nextLine();//Advance the scanner
  }

这篇关于如何使用Scanner检查用户输入是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆