-1
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;
}

我在 main 方法中完成了所有工作,但我想将它分开以使其更清洁。我一定做错了什么,因为现在添加方法甚至无法正常工作。例如,a = 5 + 6 应该打印地图 {a=11}

4

1 回答 1

3

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...)

于 2013-10-26T18:34:48.650 回答