我的第一个java项目

时间:2014-09-06 11:57:04

标签: java string hashmap

我正在为大学制作Java项目,我有这样的输入:

i 4         //that are the iteration 

a nissan car motor -1      // "a" means add operation "nissan" is the element and "car e motor"  
                                         // are the tags associated to nissan

a apple fruit iphone macbook -1  

a peach fruit color -1   

s fr -1               // "s" is the subtag that I have to find in the tag

i 3

a soccer ball player -1

a volley ball shoes -1

s bal -1

END                // "END" is the end of input

输出:

2

2

因为在第一次迭代时它找到了两个标签以“fr”开头的元素 在第二次迭代中,它找到了两个标签以“bal”开头的元素。

class main 
{
    private static boolean trovato;

    public static void main (String args [] ) throws IOException 
    {
        HashMap<String, HashSet<String>> map = new HashMap <String,HashSet<String>> (); 
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        HashSet<String> totale = new HashSet <String> () ;

        String line ;
        String numiter;
        Integer numiter2  = 0 ;
        String[] parts = null ;

        HashSet<String> hs   = new HashSet<String>  () ;
        HashSet<String> tmp = new HashSet<String>  () ;
        Vector <Integer> conti = new Vector<Integer> ();

        boolean entrato = false ;

        line = stdin.readLine();

        while (!line.equals("<END>"))
        {
            if (line.startsWith("i"))
            {
                map.clear();
                hs.clear();
                totale.clear();
            }

            parts = line.split("[\\s\\-1]");      

            if (parts[0].equals("a"))               
            {

                hs.add(parts[1]);

                for (int r = 2 ; r < parts.length ; r++)    
                {

                    map.put(parts[r], hs);                                              
                }

            }


            System.out.println("totale" + totale.size ());
            if (parts[0].equals("s"))
            {
                entrato = false ;   
                for (String key : map.keySet())                                 
                {
                    if (key.startsWith(parts[1]))                                   
                    {
                        entrato = true ;            
                        totale.addAll(map.get(key));                                
                    }
                }
                System.out.println(totale.size ());
            }
            line = stdin.readLine();
        }
    }   
}

代码有效,但我的老师想要一种更有效的方法来做这件事。我不知道该怎么做。谢谢你。

1 个答案:

答案 0 :(得分:0)

供将来参考尝试让您的问题更具体。调试是你的工作;我会建议在来之前回顾课堂上教授的概念。我们更愿意回答一个比这更具体的问题。如果您需要进一步的帮助,请随时与我联系。

相关问题