Android 字符串:查找数字并创建新字符串

发布于 2024-11-27 13:08:54 字数 313 浏览 2 评论 0原文

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

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

I have a spinner that is populated with a list of strings such as "Item 1: 1.5 - 2.5" and I would like to somehow extract the number portions (1.5 - 2.5) from that string when it is selected from the spinner and then calculate the average of the two numbers.

My initial thought is to get the string when it is selected from the spinner, then use the copyValueOf method to extract just the numbers from the string, then add them to their own variables and determine the average. Unfortunately I have no idea how to set this up in code. How do I collect the numbers individually from the character array? All the numbers are 3 digits long (2.3) including the decimal, so maybe I can use getChars function on the array and get the first 3 characters into one variable and then the last 3 in another?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只等公子 2024-12-04 13:08:54
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;
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;
情感失落者 2024-12-04 13:08:54
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);

这可能是最好的解决方案,但它有效,并且我已经测试过,希望这可以帮助您。

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

This maybe the best sulotion but it works and I have tested it, hope this can help you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文