[求助]如何判断输入是字符是不是数字?
比如str=buf.readLine();
a=Integer.parseInt(str);
在中间应该加一个判断语句.如果不加.当输入的不是数字会报错的.
谢谢了!
----------------解决方案--------------------------------------------------------
你可以用equals或者正则表达式来判断,反正一共就10个数字
----------------解决方案--------------------------------------------------------
我遇到过这种情况...做的是一个类似excel的表格...捕捉错误也不能解决问题...
----------------解决方案--------------------------------------------------------
正则表达式?...还没听过,真是谢谢了.
今天看了一下资料.学习了一下,好像还是有点问题-_-!
继续学习中...
import java.io.*;
import java.util.regex.*;
public class example {
public static void main(String []args)throws IOException {
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
String str;
int a=0;
while(true)
{
System.out.print("Please input your mark:");
str=buf.readLine();
String regEx="[0-9]+";//表示一个或多个数字
Pattern p=Pattern.compile(regEx); //编译成模式
Matcher m=p.matcher(str); //创建一个匹配器
boolean rs=m.matches();
if(rs)a=Integer.parseInt(str);
if(a<=100&&a>=0)break;
System.out.println("You inputed a wrong number!\nPlease input again!");
}
if(a>=90)System.out.println("A");
else if(a>=75&&a<=98)System.out.println("B");
else if(a>=60&&a<=74)System.out.println("C");
else System.out.println("D");
}
}
----------------解决方案--------------------------------------------------------
何必走那么多弯路呢
使用 Character.isDigit(char ch) 这样不是更省事吗?
----------------解决方案--------------------------------------------------------
楼上的办法也不一定对,因为-1235也是数字,但是-不是数字
所以最好的办法就是
Integer.parseInt()
然后捕获NumberFormatException异常来看是不是数字
----------------解决方案--------------------------------------------------------
......刚刚开始接触.什么都不懂-_-!
先试试.谢谢各位了.
----------------解决方案--------------------------------------------------------
用正则表达式
^[A-Za-z]+$ //匹配由26个英文字母
^[0-9]+$ //匹配数字
----------------解决方案--------------------------------------------------------
这两天又看了一下.终于可以了.真高兴~~~
4#中的正规表达式没问题,问题出在int a=0;的初始化上.如果输入的不是数字,但a==0;当然就break了.现把它int a=-1就好啦~~~
昨天看了一下异常处理,也得啦~~~ ^-^
但.....equals();还不行.
是不知道该用哪个类中的equals方法.
找API找到头晕眼花也没找到...
好像觉得用equals();不太好处理...
//异常处理
import java.io.*;
public class Hello {
public static void main(String []args)throws IOException {
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
String str;
int a=-1;
while(true)
{
System.out.print("Please input your mark:");
str=buf.readLine();
try{
a=Integer.parseInt(str);
}
catch(NumberFormatException e){}//前者异常类,e为对象名
finally{
if(a<=100&&a>=0)break;
System.out.println("You inputed a wrong number!\nPlease input again!");
System.out.println("");
}
}
if(a>=90)System.out.println("A");
else if(a>=75&&a<=98)System.out.println("B");
else if(a>=60&&a<=74)System.out.println("C");
else System.out.println("D");
}
}
----------------解决方案--------------------------------------------------------