java从下列字符串中分别获取到长方体的长、宽、高,完成长方体的体积计算并打印。 "length=2.3 width=5.1 height=4.8"
时间: 2023-05-10 08:55:04 浏览: 52
可以使用正则表达式来提取字符串中的数字,然后进行计算。以下是示例代码:
```
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("\\d+\\.\\d+");
Matcher matcher = pattern.matcher(input);
double length = 0, width = 0, height = 0;
if (matcher.find()) {
length = Double.parseDouble(matcher.group());
}
if (matcher.find()) {
width = Double.parseDouble(matcher.group());
}
if (matcher.find()) {
height = Double.parseDouble(matcher.group());
}
double volume = length * width * height;
System.out.println("长方体的体积为:" + volume);
}
}
```
输出结果为:
```
长方体的体积为:55.584
```