如何在字符串中识别2个单独的2位数字?

时间:2019-01-18 16:21:26

标签: java io stream

我试图找到一种方法来识别string中的1或2位数字(不能有3位数字),将它们加在一起,因此它们必须在80到95之间。

由于某种原因,代码无法正常工作,因为即使在理论上应该返回true,它也始终返回false。

例如“ Hi 57 how are you 30”返回false

提前感谢您的帮助!

("line" is the name of the String.)

public boolean isDig(){
    int total=0;
    int h;
    int length = line.length();
    for(h=0; h < length-1; h++) {
        if (Character.isDigit(line.charAt(h))){
            if (Character.isDigit(line.charAt(h+1))){
                if (Character.isDigit(line.charAt(h+2))){
                    return false;
                }
                else {
                    total= total+(line.charAt(h)+line.charAt(h+1));
                    h++;
                }
            }
            else {
                total= total+(line.charAt(h)); 
            }
        }

    if (total>=80 && total<=95){
        return true;
    }
    else {
        return false;
        }   
}

5 个答案:

答案 0 :(得分:1)

代码中的主要问题是line.charAt(h)不是位置h上的数字的数值。它是代码点值,例如'0'是48。

获取数值的最简单方法是Character.getNumericValue(line.charAt(h)),在其他地方也是如此。

您还缺少对中第一个数字乘以10的结果。


假设您知道字符串是有效的,那么只需在字符串中添加任何个数字就很容易了。从获得总和的角度来看,它们是2位还是3位的事实并不重要。

int total = 0;
for (int i = 0; i < line.length(); ) {
  // Skip past non-digits.
  while (i < line.length() && !Character.isDigit(line.charAt(i))) {
    ++i;
  }

  // Accumulate consecutive digits into a number.
  int num = 0;
  while (i < line.length() && Character.isDigit(line.charAt(i))) {
    num = 10 * num + Character.getNumericValue(line.charAt(i));
  }

  // Add that number to the total.
  total += num;
}

答案 1 :(得分:0)

您应使用正则表达式进行此类解析:

public class Example {

    public static void main(String[] args) {
        String input = "Hi 57 how are you 30";
        System.out.println(process(input));
    }

    private static boolean process(String input) {
        Pattern pattern = Pattern.compile(".*?(\\d+).*?(\\d+)");
        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {
            int one = Integer.parseInt(matcher.group(1));
            int other = Integer.parseInt(matcher.group(2));
            System.out.println(one);
            System.out.println(other);

            int total = one + other;
            return total >= 80 && total <= 95;
        }

        return false;
    }
}

输出:

  

57

     

30

     

true

答案 2 :(得分:0)

使用正则表达式的一种可能解决方案。

public static boolean isValid(String str) {
    // regular expression matches 1 or 2 digit number
    Matcher matcher = Pattern.compile("(?<!\\d)\\d{1,2}(?!\\d)").matcher(str);
    int sum = 0;

    // iterate over all found digits and sum it
    while (matcher.find()) {
        sum += Integer.parseInt(matcher.group());
    }

    return sum >= 80 && sum <= 95;
}

答案 3 :(得分:0)

Let a java.util.Scanner do the work:

public boolean scan(String line) {
    Scanner scanner = new Scanner(line);
    scanner.useDelimiter("\\D+");
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int sum = a + b;
    return sum >= 80 && sum <= 95;
}

The invocation of .useDelimiter("\\D+") delimits the string on a regular expression matching non-digit characters, so nextInt finds the next integer. You'll have to tweak it a bit if you want to pick up negative integers.

答案 4 :(得分:0)

您可以通过测试每个String元素上的Integer.parseInt()方法,将String转换为Array并测试以查看String中的每个元素(以空格分隔)是否为Digit。下面是一个示例:

public static boolean isDig(String theString) {
    String[] theStringArray = theString.split(" ");
    ArrayList<Integer> nums = new ArrayList<Integer>();
    for(int x = 0; x < theStringArray.length; x++) {
        String thisString = theStringArray[x];
        try {
            int num = Integer.parseInt(thisString);
            nums.add(num);
        }catch(NumberFormatException e) {
            continue;
        }
    }
    int total = 0;
    for(int num: nums) {
        total += num;
    }
    if(total >= 80 && total <= 95) {
        return true;
    }
    else {
        System.out.println(total);
        return false;
    }
}

我们首先根据空白将原始String拆分为Array。然后,我们创建一个ArrayList,它将String中的每个数字添加到其中。然后,我们创建一个for循环以查看Array中的每个单独的String,并设置一个try-catch块。如果我们可以使用Integer.parseInt()方法将数字转换为整数,则将其添加到ArrayList中。如果没有,我们将捕获异常并使用“ continue”语句继续循环。一旦退出循环,我们可以创建一个名为“ total”的变量,并创建另一个for循环,以便将ArrayList中的每个数字加到总数上。如果总数大于/等于80且小于/等于95,我们将返回True,否则将返回false。让我们测试一下代码:

String digitTest = "There is a digit here: 50 and a digit here 45";
System.out.println(isDig(digitTest));

数字50和45应该等于95,我们的结果是:

true
相关问题