1

I have tried to split a sentence into two words, I tried some logic for the solution. But my code show me an error
See this is my code:

import com.eg.*;
import java.util.*;
import java.io.*;

public class DiskSpace {


    public static void main(String[] args) {
        try
        {
            HashMap map=new HashMap();
            Process p=Runtime.getRuntime().exec("cscript C:\\eGurkha\\lib\\vmgfiles\\win\\eg_diskspace.vbs");
            BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
            String lines=rd.readLine();

            while(lines!=null)
            {
                String[] words=lines.split(":",2);
                map.put(words[0], words[1]);
                lines=rd.readLine();                
            }
            System.out.println(map.size());
            Iterator it=map.entrySet().iterator();
            while(it.hasNext())
            {
                Map.Entry str=(Map.Entry)it.next();
                System.out.println(str.getKey());
                System.out.println(str.getValue());
            }


        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }

}

When I compile the above code it show me an error like below:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at com.kavi.tasks.DiskSpace.main(DiskSpace.java:20)

I couldn't find the errors, Can you please help me...

kavi
  • 55
  • 1
  • 2
  • 5

1 Answers1

1

Your problem is here :

map.put(words[0], words[1]);

If words has only a single element (i.e. there's no ":" in the String you are trying to split), words[1] would throw that exception.

You should handle it like this :

String[] words=lines.split(":",2);
if (words.length > 1)
    map.put(words[0], words[1]);
Eran
  • 387,369
  • 54
  • 702
  • 768