如何检查字符串是否包含数值

时间:2015-11-20 20:45:47

标签: java string

我想知道如何查看我的子字符串,如果它是一个数值,或者它只是单词。

例如,如果我的子串d = 150.63

我做了一些研究,我发现了Character.is Digit(),但它没有用。以下是我到目前为止所做的代码。

import java.util.*;
import java.io.*;

public class Prac34 {

    private Scanner x;

    public void openFile(){
      try{
        x=new Scanner(new File("sales.txt"));
      }
      catch (Exception e){
        System.out.println("could not find file");    
      }
    }

    public void readFile(){
      //int count=0;
      double total=0;
      while(x.hasNext()){

        String a=x.nextLine();
        int v=a.length();

        int b=a.indexOf(':');
        String c= a.substring(0,(b+1));

        String d=a.substring((b+1),v);
        double e= Double.parseDouble(d);

        if (Character.isDigit(d)) {
          total=total+e;
        }


        System.out.println(c);
        System.out.println(d);
}
}

    public void closeFile(){
      x.close();
    }
}

2 个答案:

答案 0 :(得分:1)

您可以尝试解析字符串:

try {
    double e = Double.parseDouble(d);
    total += e;
} catch (NumberFormatException ignore) {
    // Not a number, skipping
}

答案 1 :(得分:0)

使用正则表达式(正则表达式):

String text="25.54";
     if(text.replace(".","").matches("[0-9]+")){ //or you can use also "\\d+"
         System.out.println("digit");
     }else{
      System.out.println("no digit");
     }

     System.out.println(text);

同时

其中()表示无或一次

其中(*)表示无次或多次

其中( + )表示一次或多次

|||你可以成为职业here