读书人

求java中循环输入整数当输入非整数

发布时间: 2012-04-22 18:34:46 作者: rapoo

求java中,循环输入整数,当输入非整数时,怎样忽略
import java.util.*;
class A
{
public static void main(String[] args)
{
int i = 0;
Scanner sc = new Scanner(System.in);
do{
try
{
int x = sc.nextInt();
}
catch(Exception e)
{
System.out.printf("出错");
}
i ++;
}while(i<6);
}
}
怎样通过异常处理忽略输入非整数

[解决办法]
do{
try
{
int x = sc.nextInt();
}
catch(Exception e)
{
System.out.printf("出错");
throw new RunTimeException("not a int number",e);
continue;
}

[解决办法]
可以对输入的字符进行判断再接收,如果非要求的忽略,想要的则接收……
[解决办法]

探讨

可以对输入的字符进行判断再接收,如果非要求的忽略,想要的则接收……

[解决办法]
Java code
public static void main(String[] args) {        int i = 0;        Scanner sc = new Scanner(System.in);        do {            try {                String str = sc.nextLine();                int x = Integer.parseInt(str);//靠异常来处理的,你也可以用正则表达式判断啥的判断是不是可以转为整数                System.out.println(x);            } catch(Exception e) {                System.out.printf("出错");                continue;            }            i ++;        } while(i<6);    }
[解决办法]
Java code
Scanner sc = new Scanner(System.in);        while(true){            System.out.println("请输入一个整数");            String str = sc.next();            if(str.matches("[0-9]*")){                System.out.println("您很聪明输入的整数是:" + Integer.parseInt(str));            } else{                System.err.println("看清除了要输入的是整数");            }        }
[解决办法]
我只会最本的方法,转换成int判断值对不对不就行了

读书人网 >Java相关

热点推荐