【问题标题】:Android String: Find Number and Create New StringAndroid 字符串:查找数字并创建新字符串
【发布时间】:2011-08-02 03:23:03
【问题描述】:

我有一个微调器,其中填充了诸如“项目 1:1.5 - 2.5”之类的字符串列表,当从微调器中选择该字符串时,我想以某种方式从该字符串中提取数字部分 (1.5 - 2.5)然后计算两个数的平均值。

我最初的想法是从spinner中选择字符串的时候得到字符串,然后用copyValueOf方法从字符串中只提取数字,然后把它们加到自己的变量中,求平均值。不幸的是,我不知道如何在代码中进行设置。如何从字符数组中单独收集数字?所有数字都是 3 位长(2.3),包括小数,所以也许我可以在数组上使用 getChars 函数并将前 3 个字符放入一个变量中,然后将后 3 个字符放入另一个变量中?

【问题讨论】:

    标签: android arrays string spinner


    【解决方案1】:
    String s="Item 1: 1.5 - 2.5"//s=spinner.getItemAt(i)
    String newS[]=s.split(":");//newS[0]="Item 1" and newS[1]="1.5-2.5"
    String newS2[]=newS[1].split("-");//
    
    Double d1=Double.parseDouble(newS2[0]);
    Double d2=Double.parseDouble(newS2[1]);
    Double avg=(d1+d2)/2;
    

    【讨论】:

      【解决方案2】:
      String str = "Item 1: 1.5 - 2.5";
      String[] strs = str.split(":");
      
      String numberStr = (strs[strs.length - 1]).trim();
      String[] numbers = numberStr.split("-");
      
      float sum = 0f;
      for (int i = 0; i < numbers.length; i++) {
          sum = sum + Float.valueOf(numbers[i]).floatValue();
      }
      //Here, get the average of the two numbers
      float result = sum / (numbers.length);
      

      这可能是最好的解决方案,但它有效,我已经测试过了,希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-27
        • 1970-01-01
        • 2012-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        相关资源
        最近更新 更多