简体   繁体   中英

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.

For some reason, the code is not working, as it is always returning false, even when it should (in theory) return true.

ex. " Hi 57 how are you 30 " returns false

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 . It's the codepoint value, for example '0' is 48.

The easiest way to obtain the numeric value is Character.getNumericValue(line.charAt(h)) , and similarly in other places.

You're also missing the multiplication by 10 of the first digit in the pair.


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.

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

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:

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.

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. 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. We then create an ArrayList that will add each digit in the String to it. We then create a for loop to look at each individual String in the Array and we set up a try-catch block. If we can covert the digit into an int using the Integer.parseInt() method, we will add it to the ArrayList. If not, we will catch the exception and continue the loop with a "continue" statement. 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. 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. 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:

true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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