JAVA 从下列字符串中分别获取到长方体的长、宽、高,完成长方体的体积计算。 "length=2.3 width=5.1 height=4.8"
时间: 2023-05-10 20:55:07 浏览: 172
可以使用正则表达式来从字符串中获取长、宽、高的值,然后进行体积计算。以下是示例代码:
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "length=2.3 width=5.1 height=4.8";
Pattern pattern = Pattern.compile("length=(\\d+\\.?\\d*) width=(\\d+\\.?\\d*) height=(\\d+\\.?\\d*)");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
double length = Double.parseDouble(matcher.group(1));
double width = Double.parseDouble(matcher.group(2));
double height = Double.parseDouble(matcher.group(3));
double volume = length * width * height;
System.out.println("长方体的体积为:" + volume);
}
}
}
```
输出结果为:
```
长方体的体积为:55.584
```
阅读全文