0

I am trying to split an IP address by ".". But code is generating an exception.

Exception Message : "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at decimaltobinary.DecimalToBinary.main". 

Help me to solve. Here is my Code.

 String[] ipAddresses=IP.split(".");
 String ip1=ipAddresses[0];
 String ip2=ipAddresses[1];
 String ip3=ipAddresses[2];
 String ip4=ipAddresses[3];
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60

3 Answers3

3

. is special character in regular expressions. Try:

IP.split("\\.");

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Gregory Prescott
  • 574
  • 3
  • 10
1

In a regex, the token . means to match on any character. If you want to match the character literal ., you need to split on the regex \..

This means that the actual String must represent \. so you'll have to do .split("\\.").

CAD97
  • 1,160
  • 12
  • 29
0

try with (\\.) ie String[] ipAddresses=IP.split("\\.") that will give you

String[] ipAddresses=IP.split("\\.");
 String ip1=ipAddresses[0];
 String ip2=ipAddresses[1];
 String ip3=ipAddresses[2];
 String ip4=ipAddresses[3];

it should be work.

Toukea Tatsi
  • 189
  • 1
  • 5