【问题标题】:How do I identify 2 separate 2-digit numbers in a String?如何识别字符串中的 2 个单独的 2 位数字?
【发布时间】:2019-06-12 22:41:15
【问题描述】:

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

由于某种原因,代码无法正常工作,因为它总是返回 false,即使它应该(理论上)返回 true。

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

提前感谢您的帮助!

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

【问题讨论】:

  • 做一些调试,看看你的添加实际上在做什么——它可能让你吃惊。几个System.out.println 语句就足够了。
  • 你做了什么调试?您具体需要哪些帮助?你检查过total 是什么吗?
  • 请注意,如果 h == length - 2,您对第三个字符是否为数字的检查将超出字符串的末尾。即如果最后有一个两位数(例如没有任何尾随空格),它将失败。

标签: java io stream


【解决方案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;
}

【讨论】:

    【解决方案2】:

    您应该使用正则表达式进行这种解析:

    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

    是的

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        .useDelimiter("\\D+") 的调用在匹配非数字字符的正则表达式上分隔字符串,因此nextInt 查找下一个整数。如果你想取负整数,你必须稍微调整一下。

        【讨论】:

          【解决方案5】:

          您可以将 String 转换为 Array 并通过在每个 String 元素上测试 Integer.parseInt() 方法来测试 String 中的每个元素(由空格分隔)是否是数字。下面是一个例子:

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

          我们首先根据空格将原始字符串拆分为一个数组。然后我们创建一个 ArrayList 将字符串中的每个数字添加到它。然后我们创建一个 for 循环来查看 Array 中的每个单独的 String 并设置一个 try-catch 块。如果我们可以使用 Integer.parseInt() 方法将数字转换为 int,我们会将其添加到 ArrayList。如果没有,我们将捕获异常并使用“继续”语句继续循环。一旦我们跳出循环,我们可以创建一个名为“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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-03-30
            • 2019-09-10
            • 1970-01-01
            • 1970-01-01
            • 2014-07-07
            • 2020-12-16
            • 1970-01-01
            相关资源
            最近更新 更多