2017-12-22 输入常量的判定

来源:互联网 发布:xmind for mac 编辑:程序博客网 时间:2024/06/09 06:06

Scanner input = new Scanner(System.in);后用input.hasNextInt()进行判定。


下面是代码:


package day1221;import java.util.Scanner;public class Id_exerise {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("请输入4位整数会员号:");int vip = 0; //整型会员号String errorVip = ""; //非数字的会员号int errorType = 0; //错误类型,0-没有错误,1-输入的是字符串,2-非4位整数/** * Scanner内置一个数据缓冲区, * 当调用Scanner对象的hasNextInt或者nextInt方法时, * 都会触发键盘输入,从键盘输入数据以后会把数据存入缓冲区 * 这个缓存区 是以队列形式(有顺序)存在, * hasNextInt()判断这个缓存区中第一个数据是否是整型,如果是就返回true * 否则返回false, *  * nextInt() 以整型的形式取出缓存区的第一个数据,如果这个数据不是整型,则抛出异常 * 如果是整型,则作为nextInt()的返回值返回给调用者。 */if(input.hasNextInt()){vip = input.nextInt();if(vip < 1000 || vip > 9999){errorType = 2;}}else{errorVip = input.next();errorType = 1;}System.out.print("请输入积分:");int score = input.nextInt();if(errorType == 1){System.out.println("客户号" + errorVip + "是无效会员号");}else if(2 == errorType){System.out.println("客户号" + vip + "是无效会员号");}else{System.out.println(vip);}}}