【发布时间】:2020-01-13 20:12:40
【问题描述】:
我的任务是使用一堆整数来计算给定分子的分子量。我应该使用数组自己实现 IntStack 类。然后我应该创建一个将字符串作为输入并评估分子的类。输入中的唯一字符将是左括号和右括号、数字 2-9 以及 H(氢)、C(碳)和 O(氧)。我得到了三种元素的分子量分别为 1、12 和 16。
public class IntStack
{
private int[] stack;
public int index;
public IntStack()
{
stack = new int[100];
index = -1;
}
public void push(int x)
{
stack[index + 1] = x;
index++;
}
public int pop()
{
if (index == -1)
{
return -1;
}
int num = stack[index];
index--;
return num;
}
public int peek()
{
if (index == -1)
{
return 0;
}
return stack[index];
}
}
import java.util.Scanner;
public class MolecularMass
{
private static IntStack stack;
public static void main(String[] args)
{
stack = new IntStack();
Scanner kb = new Scanner(System.in);
System.out.print("Enter the molecule: ");
String input = kb.nextLine();
int result = evaluate(input);
System.out.println("The Molecular Mass of " + input + " is " + result);
}
public static int evaluate(String s)
{
int answer = 0;
int num = 0;
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
switch(c)
{
case '2':
num = stack.pop();
num *= 2;
stack.push(num);
break;
case '3':
num = stack.pop();
num *= 3;
stack.push(num);
break;
case '4':
num = stack.pop();
num *= 4;
stack.push(num);
break;
case '5':
num = stack.pop();
num *= 5;
stack.push(num);
break;
case '6':
num = stack.pop();
num *= 6;
stack.push(num);
break;
case '7':
num = stack.pop();
num *= 7;
stack.push(num);
break;
case '8':
num = stack.pop();
num *= 8;
stack.push(num);
break;
case '9':
num = stack.pop();
num *= 9;
stack.push(num);
break;
case 'C':
stack.push(12);
break;
case 'H':
stack.push(1);
break;
case 'O':
stack.push(16);
break;
case '(':
stack.push(0);
break;
case ')':
int result = 0;
while(stack.peek() != 0)
{
result += stack.pop();
}
int throwaway = stack.pop();
stack.push(result);
break;
default:
break;
}
}
for(int i = 0; i < stack.index; i++)
{
answer += stack.pop();
}
return answer;
}
}
它应该运行如下:
输入分子:((CH)2(OH2H)(C(H))O)3
((CH)2(OH2H)(C(H))O)3的分子量为222
我不断得到分子质量为 0 或 1
编辑:这是我的评估方法算法: 如果字符是化学元素,程序会推动元素的分子量。 如果字符是一个左括号,则程序将 0 压入堆栈。 如果字符是右括号,则程序将括号内的所有内容相加,直到到达左括号(存储为 0) 如果字符是一个数字,它会弹出堆栈中的数字,将其乘以输入的数字,然后将其推回堆栈 最后,它将堆栈中的所有内容相加并返回结果。
【问题讨论】:
-
你的问题是?
-
对不起,我忘了把我得到的输出
-
你试过使用调试器吗?
-
你应该使用
substring和indexOf来做你的计算而不是switch。