1

I am trying to create a program for taking ad IP address as input and give Class, netID, and hostID as output. I am having a problem in taking IP address as String input in the program.

This is the snap of the error i am getting

Error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756)
    at java.base/java.lang.String.substring(String.java:1902)
    at cnPrac6.classFromDecimal(cnPrac6.java:7)
    at cnPrac6.main(cnPrac6.java:94)

Given below is the part of code i am getting error in:

public static void main(String[] args) {
            Scanner sc= new Scanner(System.in);
            String ipClassD = "";
            String ipClassB = "";
            System.out.print("In which category you address is: \n 1. Decimal \n 2. Binary \n");
            int choice = sc.nextInt();
            System.out.print("Enter your address: ");  
            String str= sc.nextLine();
            System.out.print("\n");
            
            switch (choice) {
              case 1:
                  ipClassD = classFromDecimal(str); 
                  System.out.println("Given IP address belings to Class "+ipClassD);
                  seprate(str,ipClassD);
                break;

Following the the full code

import java.util.*;

public class cnPrac6 {
        static String classFromDecimal(String str){ 

            int index = str.indexOf('.');
            String ipsub = str.substring(0,index); 
            int ip = Integer.parseInt(ipsub); 
            if (ip>=1 && ip<=126) 
                return "A"; 
            else if (ip>=128 && ip<=191) 
                return "B"; 
            else if (ip>=192 && ip<223) 
                return "C"; 
            else if (ip >=224 && ip<=239) 
                return "D"; 
            else
                return "E"; 
        } 

        static String classFromBinary(String str){ 
 
            if (str.charAt(0)=='0') 
                return "A"; 
            else if (str.charAt(0)=='1' && str.charAt(1)=='0') 
                return "B"; 
            else if (str.charAt(0)=='1' && str.charAt(1)=='1' && str.charAt(2)=='0') 
                return "C";
            else if (str.charAt(0)=='1' && str.charAt(1)=='1' && str.charAt(2)=='1' && str.charAt(3)=='0') 
                return "D";
            else if (str.charAt(0)=='1' && str.charAt(1)=='1' && str.charAt(2)=='1' && str.charAt(3)=='1' && str.charAt(4)=='1') 
                return "E";
            else return "Error wrong address";
        }
        
        static void seprate(String str, String ipClass){  
            String network = "", host = ""; 
      
            if(ipClass == "A"){ 
                int index = str.indexOf('.'); 
                network = str.substring(0,index); 
                host = str.substring(index+1,str.length()); 
            }
            else if(ipClass == "B"){      
                int index = -1;  
                int dot = 0;  
                for(int i=0;i<str.length();i++){ 
                    if(str.charAt(i)=='.'){ 
                        dot +=1; 
                        if(dot==2){ 
                            index = i; 
                            break; 
                        } 
                    } 
                } 
                network = str.substring(0,index); 
                host = str.substring(index+1,str.length()); 
            }
            else if(ipClass == "C"){ 
                int index = -1;  
                int dot = 0;  
                for(int i=0;i<str.length();i++){ 
                    if(str.charAt(i)=='.'){ 
                        dot +=1; 
                        if(dot==3){ 
                            index = i; 
                            break;                      
                        } 
                    } 
                } 
                network = str.substring(0,index); 
                host = str.substring(index+1,str.length()); 
            }
            else if(ipClass == "D" || ipClass == "E"){ 
                System.out.println("No network or host ID"); 
                return; 
            } 
            System.out.println("Network ID is "+network); 
            System.out.println("Host ID is "+host); 
        } 
        
        public static void main(String[] args) {
            Scanner sc= new Scanner(System.in);
            String ipClassD = "";
            String ipClassB = "";
            System.out.print("In which category you address is: \n 1. Decimal \n 2. Binary \n");
            int choice = sc.nextInt();
            System.out.print("Enter your address: ");  
            String str= sc.nextLine();
            System.out.print("\n");
            
            switch (choice) {
              case 1:
                  ipClassD = classFromDecimal(str); 
                  System.out.println("Given IP address belings to Class "+ipClassD);
                  seprate(str,ipClassD);
                break;
              case 2:
                  ipClassB = classFromBinary(str); 
                  System.out.println("Given IP address belings to Class "+ipClassB);
                  seprate(str,ipClassB);
                break; 
              default:
                System.out.println("Enter correct option");
            }
        } 
    } 
lczapski
  • 3,644
  • 3
  • 10
  • 26
  • 1
    Check what `str` contains. I'm pretty sure it contains only the newline character that you entered when you gave the input for `choice` and that `nextInt()` does not consume, and therefore it's skipping your IP address input entirely. See [this](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo). – JustAnotherDeveloper Sep 19 '20 at 08:31
  • Second input is not working. write code like this : System.out.print("Enter your address: "); sc.nextLine(); String str = sc.nextLine(); System.out.print("\n"); – Santosh Vishwakarma Sep 19 '20 at 09:02
  • What happens if str passed in classFromDecimal() doesn't have a period in it? – NomadMaker Sep 19 '20 at 10:14

2 Answers2

1

The problem is in getting input.When you are using sc.nextInt(),it takes an integer input until encountering a space.If it encounters space,it stops scanning input.

After scanning integer , still scanner is in same line ,it will not go to next line until we read the entire line.

So, scan the entire line using sc.nextLine() after getting integer input.

Here, you can find code.

int choice = sc.nextInt();                 // getting integer
sc.nextLine();                             // passing this line
System.out.print("Enter your address: ");  // scanner is in next Line
String str= sc.nextLine();                 // reading the ip address
Kaviarasu
  • 68
  • 4
  • Another option might be to use nextLine instead of nextInt and then to parse the int after trimming the string. In that case it would need to be in a try/catch in case the input cannot be parsed. – Omar Abdel Bari Sep 19 '20 at 11:46
0

The reason why it is failing is that the code, String str= sc.nextLine() is consuming the dangling new line character (when you press Enter) from the previous input. For the previous input, you are using sc.nextInt() which is consuming the integer value but not newline character.

Replace

int choice = sc.nextInt();

with

int choice = Integer.parseInt(sc.nextLine());
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72