简体   繁体   English

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

[英]How do I identify 2 separate 2-digit numbers in a String?

I am trying to find a way to identify 1 or 2 digit numbers in a string (there can't be any 3 digit numbers), add them together so they must be between 80 and 95. 我试图找到一种方法来识别string 1或2位数字(不能有任何3位数字),并将它们加在一起,因此它们必须在80到95之间。

For some reason, the code is not working, as it is always returning false, even when it should (in theory) return true. 由于某种原因,该代码无法正常工作,因为即使在理论上应该返回true,它也始终返回false。

ex. 恩。 " Hi 57 how are you 30 " returns false Hi 57 how are you 30 ”返回假

Thank you in advance for your help! 预先感谢您的帮助!

("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;
        }   
}

The main problem in the code is that line.charAt(h) isn't the numeric value of the digit at position h . 代码中的主要问题是line.charAt(h)不是位置h处的数字的数值。 It's the codepoint value, for example '0' is 48. 它是代码点值,例如'0'为48。

The easiest way to obtain the numeric value is Character.getNumericValue(line.charAt(h)) , and similarly in other places. 获取数值的最简单方法是Character.getNumericValue(line.charAt(h)) ,在其他地方也是如此。

You're also missing the multiplication by 10 of the first digit in the pair. 您还缺少对中第一个数字乘以10的乘积。


Assuming you know that the string is valid, it's easy enough just to add up any numbers in the string. 假设您知道字符串是有效的,那么只需将字符串中的任何数字相加就很容易了。 The fact that they are 2 or 3 digits doesn't really matter from the perspective of obtaining the sum. 从获得总和的角度来看,它们是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;
}

You should use a regex for this kind of parsing : 您应该使用正则表达式进行这种解析:

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;
    }
}

Output : 输出:

57 57

30 三十

true 真正

One of the possible solution it to use Regual Expression . 使用正则表达式的一种可能解决方案。

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;
}

Let a java.util.Scanner do the work: 让一个java.util.Scanner完成工作:

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. 调用.useDelimiter("\\\\D+")在与非数字字符匹配的正则表达式上对字符串定界,因此nextInt查找下一个整数。 You'll have to tweak it a bit if you want to pick up negative integers. 如果要提取负整数,则必须稍作调整。

You could convert the String into an Array and test to see if each element in the String (separated by a space) is a Digit by testing the Integer.parseInt() method on each String element. 您可以通过测试每个String元素上的Integer.parseInt()方法,将String转换为Array并测试以查看String中的每个元素(以空格分隔)是否为Digit。 Here is an example below: 下面是一个示例:

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;
    }
}

We first split the original String into an Array based on the empty spaces. 我们首先根据空白将原始String拆分为Array。 We then create an ArrayList that will add each digit in the String to it. 然后,我们创建一个ArrayList,它将String中的每个数字添加到其中。 We then create a for loop to look at each individual String in the Array and we set up a try-catch block. 然后,我们创建一个for循环以查看Array中的每个单独的String,并设置一个try-catch块。 If we can covert the digit into an int using the Integer.parseInt() method, we will add it to the ArrayList. 如果我们可以使用Integer.parseInt()方法将数字转换为整数,则将其添加到ArrayList中。 If not, we will catch the exception and continue the loop with a "continue" statement. 如果没有,我们将捕获异常并使用“ continue”语句继续循环。 Once we break out of the loop, we can create a variable called "total" and create another for loop in order to add each digit in the ArrayList to the total amount. 一旦退出循环,我们可以创建一个名为“ total”的变量,并创建另一个for循环,以便将ArrayList中的每个数字加到总数上。 If the total is greater than/equal to 80 and less than/equal to 95, we will return True, or else we will return false. 如果总数大于/等于80且小于/等于95,我们将返回True,否则将返回false。 Let's test the code: 让我们测试一下代码:

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

The numbers 50 and 45 should equal 95 and our result is: 数字50和45应该等于95,我们的结果是:

true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM