public static void main(String args[])
{
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens[i].charAt(0) == '+')
{
addition(tokens, value);
break;
}
else if(i==tokens.length-1)
{
System.out.println("No operation");
break;
}
}
map.put(tokens[0], value);
System.out.println(map);
}
if(line.equals("clear"))
{
clear(map);
}
if(line.equals("var"))
{
variableList(map);
}
}
}
public static int addition(String[] a, int b)
{
for(int j=0; j<a.length; j++)
{
if(Character.isDigit(a[j].charAt(0)))
{
int add = Integer.parseInt(a[j]);
b = b + add;
}
}
return b;
}
I had this working all in the main method, but I wanted to separate it to make it cleaner. I must've done something wrong because now the addition method doesn't even function properly. For example, a = 5 + 6 should print the map {a=11}
This is the problem:
addition(tokens, value);
You're calling the method, but ignoring the return value. You should always be wary when you're calling a non-void method, but ignoring the return value. I suspect you want:
value = addition(tokens, value);
(There are various other stylistic changed I'd make - probably starting with changing the loop in addition
to use an enhanced for
loop: for (String item : a)
etc. But this should at least get you started...)
See more on this question at Stackoverflow