0
好吧,我正在Java中构建一个简单的PostFix计算器,并且我被要求为它创建一对功能,我正在努力处理的是内存。我听说你可以用HashMap来做,我也研究过它,但我不认为我很了解如何将它实现到我的程序中。该计划的工作方式是,用户将启动它,它会说,它的后缀计算器,将被提示这样的输入:如何使用散列表为计算器创建内存?
java PostfixCalc
Integer Postfix calculator with memory
>
但他有一个变量分配给他的输入选项,例如:
> a = 3 5 + 1 -
7
> bee = a 3 *
21
> a bee +
28
> bee 3 %
0
> a = 4
4
> 57
57
> 2 c +
c not found
> mem
a: 4
bee: 21
> exit
这是我的代码到目前为止。我想我应该标记输入并将其放入数组列表中以获取变量名称,除非是更好的方法。
import java.util.*;
import java.io.*;
public class Program6
{
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("RPN command line calculator");
Scanner scan = new Scanner(System.in);
System.out.print(">");
while(scan.hasNextLine())
{
System.out.print("> ");
String a = scan.nextLine();
String b = "quit";
String c = "mem";
String d = "clear";
if(a.equals(b))
{
System.exit(0);
}
else
{
System.out.println(compute(a));
}
System.out.print(">");
}
}
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
}
}
else
{
return "Error";
}
Stack<String> tempList = new Stack<String>();
Iterator<String> iter = processedList.iterator();
while (iter.hasNext())
{
String temp = iter.next();
if (temp.matches("[0-9]*"))
{
tempList.push(temp);
}
else if (temp.matches("[*-/+]"))
{
if (temp.equals("*"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls * rs;
tempList.push("" + result);
}
else if (temp.equals("-"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls - rs;
tempList.push("" + result);
}
else if (temp.equals("/"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls/rs;
tempList.push("" + result);
}
else if (temp.equals("+"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls + rs;
tempList.push("" + result);
}
}
else
{
return "Error";
}
}
return tempList.pop();
}
}
private static String HashMap(String q)
{
List<String> memory = new ArrayList<String>();
if(!q.isEmpty())
{
StringTokenizer var = new StringTokenizer(q);
while(q.hasMoreTokens())
{
memory.add(q.nextToken());
}
}
HashMap h = new HashMap();
}
}//end of class
Map接口和HashMap实现已经是Java的一部分。 Map resultsMap = new HashMap <>();然后,当您确定 = 时,如果您需要查找的值,请使用resultsMap.get()(如果不存在,则返回null,请参阅上面的c),并使用resultsMap.put(,对的列表。 –
JimW
2015-04-01 19:23:48