我现有一个String,"a091b",我想要对这个String进行判断,其中只能有数字,不能有字母,如果出现非数字就提示用户此String错误。请教各位大虾帮忙。
另外,String.split(),和String.indexof()是怎么个用法,希望不要用太专业的解释告诉我,最好通俗易懂一点,谢谢。

解决方案 »

  1.   

    使用Long.parseLong(str)是否有异常判断
      

  2.   

    正则式太麻烦,而且效率有问题。
    如果需求只是那么简单的话,象Long/Integer/Float....都有 valueOf(String s)的方法,你可以调用一下,然后catch NumberFormatException.
      

  3.   

    public String[] split(String regex)
    Splits this string around matches of the given regular expression. 
    This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. The string "boo:and:foo", for example, yields the following results with these expressions: Regex Result 
    : { "boo", "and", "foo" } 
    o { "b", "", ":and:f" } 
      

  4.   

    String s = "a091b";
    try {
        Long.parseLong(s);
        System.out.println("成功.");
    } catch(Exception e) {
        System.out.println("错误!字符串里只能有数字.");
    }
      

  5.   

    for (int i = 0; i < string.length(); i++){
    if (string.charAt(i) > 32 && cityname.charAt(i) < 42)

      System.out.println("ok");
     }
     else 
      System.out.println("error");
    }
      

  6.   

    各位误解我的意思了,我的意思是有一个String str="01,02,03,04,05,06#01",就和双色球一样的,中间用","隔开的,我现在要做个判断,输入进来的字符串必须要是这种模式的,各位大大帮帮忙吧
      

  7.   

    分解成 char[] ,分别判断编码但是完全没有效率,呵呵~~
      

  8.   

    8楼的方法还是有点问题,如果数字表达式超出了 long 的范围呢?
      

  9.   

    我认为最简单的办法就是看是否能转换成数字类型,能就成功,不能就错误
    ChDw(米) 
    woolceo(努力升仙) 
    同意
      

  10.   

    6楼请执行下列程序
    public static void main (String[] args) {
            String tmp = "1a1";
            long start = System.currentTimeMillis();
            
            String regEx = "^\\d+$";
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(tmp);
            System.out.println(matcher.find());
            System.out.println("Use RegEx cost: " + (System.currentTimeMillis() - start));
            
            start = System.currentTimeMillis();
            try {
                Long.valueOf(tmp);
            } catch (NumberFormatException nfe) {
                System.out.println("Use Exception catching cost: " + (System.currentTimeMillis() - start));
            }
        }
      

  11.   

    Chapter 8. Exceptions
    When used to best advantage, exceptions can improve a program's readability, reliability, and maintainability. When used improperly, they can have the opposite effect. This chapter provides guidelines for using exceptions effectively.
    --------------------------------------------------------------
    From <<Effective Java Programming Language Guide>>
    --------------------------------------------------------------这两条是对异常的一点说明
    &#8226; Because exceptions are designed for use under exceptional circumstances, few, if any, JVM implementations attempt to optimize their performance. It is generally expensive to create, throw, and catch an exception.
    &#8226; Placing code inside a try-catch block precludes certain optimizations that modern JVM implementations might otherwise perform.如果你要简单的话,异常可以;但你要保证是有质量的,高效的代码,建议使用正则。Exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow.
      

  12.   

    System.out.println("01104548".match("\\d+"));
      

  13.   

    楼上的想说明什么问题,两个测试结果有区别吗???
    附:
    java.lang.String:
        public boolean matches(String regex) {
            return Pattern.matches(regex, this);
        }java.util.regex.Pattern
        public static boolean matches(String regex, CharSequence input) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(input);
            return m.matches();
        }孟子云:尽信“书”不如无“书”
    以下是连续5次的测试结果
    Use RegEx cost: 47
    Use Exception catching cost: 0Use RegEx cost: 32
    Use Exception catching cost: 0Use RegEx cost: 32
    Use Exception catching cost: 0Use RegEx cost: 46
    Use Exception catching cost: 16Use RegEx cost: 47
    Use Exception catching cost: 0
    实在看不出正则式高效在哪?
    原因自己看java.util.regex包源码!
      

  14.   

    return strExp.matches("^[0-9]*$");
      

  15.   

    各位老大们,不要再争了,快告诉我我刚才提问的解决方法吧,------------------------各位误解我的意思了,我的意思是有一个String str="01,02,03,04,05,06#01",就和双色球一样的,中间用","隔开的,我现在要做个判断,输入进来的字符串必须要是这种模式的,各位大大帮帮忙吧
      

  16.   

    呵呵,实际上一句话也就搞定了阿
    public class Test { /**
     * @param args
     */
    public static void main(String[] args) {
    String s = "name";
    if(!s.matches("^\\d")){
    System.out.println("Input error!");
    }
    }}
      

  17.   

    两种方案
    要效率的,用StringTokenizer把原字符串按","分割成若干段,然后逐段按catch exception判断。
    要遵循principle的写出优雅代码的,自己写正则。
      

  18.   

    package test;import java.util.regex.Pattern;public class Test3 {    static void check(String str) {
            if (Pattern.matches("\\d\\d,\\d\\d,\\d\\d,\\d\\d,\\d\\d,\\d\\d#\\d\\d", str)) {
                System.out.println("good !");
            } else {
                System.out.println("bad !");
            }
        }    public static void main(String[] args) {
            check("01,02,03,04,05,06#01");
            check("X1,02,03,04,05,06#01");
        }}
      

  19.   

    千万别用toChar的方法,超级笨,
    用Long.parseLong(s)方式可以,
    不过我个人更推荐用正则表达式,
    给你个实例------------------------------------------
    import java.awt.Dimension;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;public class Test extends JFrame implements KeyListener {
     JTextField tf = new JTextField(20); int limit = 10; public Test() {  JPanel jp = new JPanel();
      tf.addKeyListener(this);
      jp.add(tf);
      getContentPane().add(jp);
      setDefaultCloseOperation(EXIT_ON_CLOSE);  setSize(new Dimension(400, 300));
      setVisible(true);
     } public void keyTyped(KeyEvent e) {
      if (tf.getText().length() >= limit) {
       getToolkit().beep();
       e.consume();
       System.out.println("Value cannot greater than 10");
       JOptionPane.showMessageDialog(null, "Value cannot greater than 10");
      }
     } public void keyReleased(KeyEvent e) {
     } public void keyPressed(KeyEvent e) {
     } public static void main(String[] a) {
      new Test();
     }
    }