题目描述:
给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)
例如C6H5OH的分子量为94.108g/mol
思路:
先分解分子的每个元素,如:C6H5OH 分解为 C6 , H5 , O , H
再通过 switch 获得相应元素的原子量 × 强制转换得到的元素个数,再累加起来。
元素后面不跟数字的直接相加,有数字的先拆出来转换类型
Java代码:
import java.util.Scanner;
public class Ma {
public static void main(String[] args) {
//字母位置
int temp = 0;
//分子量
double coun = 0;
//输入的分子式
String str = "";
//分解的元素
String s = "";
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine().trim();
for (int i = 0; i < str.length(); i++) {
// 判断字母
if (str.charAt(i) >= 65 && str.charAt(i) <= 80) {
// 取元素和后面的数字如:C6
s = str.substring(temp, i);
temp = i;
System.out.println(s);
if (s.length() >= 2) {
// 后面跟多位数字
coun += Ma.name(s.charAt(0)) * Double.parseDouble(s.substring(1, s.length()));
} else if (s.length() == 1) {
// 不跟数字
coun += Ma.name(s.charAt(0));
}
}
}
// 取最后一个元素和后面的数字如:C6
s = str.substring(temp, str.length());
System.out.println(s);
if (s.length() >= 2) {
// 后面跟多位数字
coun += Ma.name(s.charAt(0)) * Double.parseDouble(s.substring(1, s.length()));
} else if (s.length() == 1) {
// 不跟数字
coun += Ma.name(str.charAt(str.length() - 1));
}
System.out.println(coun+"g/mol");
}
// 返回相应的原子量
public static double name(char s) {
switch (s) {
case 'C':
return 12.01;
case 'H':
return 1.008;
case 'O':
return 16.00;
case 'N':
return 14.01;
default:
break;
}
return 0;
}
}
先写下来能实现的,还没测试是否能通过。。。。。。