Home > Software engineering >  I'm having trouble separating numbers with .'s in between
I'm having trouble separating numbers with .'s in between

Time:05-11

So, I've been trying to make a program that can change a regular ip (182.66.24.45 as example) to a binary number. I've got the converting part done, its just me trying to separate the .'s is not doing too well for me. When I try converting the str into an int, then separating the .'s, it just comes out with the errors

convertip.java:24: error: incompatible types: String[] cannot be converted to String
        int[] ipint = Integer.parseInt(ipstr.split("."));
                                                  ^
convertip.java:25: error: incompatible types: int[] cannot be converted to int
        convertbinary(ipint);
                      ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

And here is all the code I have

    public static void printbinary(int binary[], int id){
        for (int i = id; i>=0; i--){
            System.out.print(binary[i]   "");
        }
    }
    public static void convertbinary(int num){
        int[] binary = new int[35];
        int id = 0;
  
        // Number should be positive
        while (num > 0) {
            binary[id  ] = num % 2;
            num = num / 2;
        }
        printbinary(binary, id);
    }
    public static void main(String[] args){
        Scanner ip = new Scanner(System.in);
        System.out.println("Enter in the ip.");
        String ipstr = ip.nextLine();
        int[] ipint = Integer.parseInt(ipstr.split("."));
        convertbinary(ipint);
    }

CodePudding user response:

You could certainly write a method that took a whole array of strings and converted them all to ints, return the int[], but that's not what Integer.parseInt does. It takes one String and converts it to one int.

int[] parseInts(String... strings) {
    int[] result = new int[strings.length];
    for (int i = 0; i < strings.length; i  ) {
        result[i] = Integer.parseInt(strings[i]);
    }
    return result;
}

You could then write:

String ipstr = "182.66.24.45";
int[] ipint = parseInts(ipstr.split("\\."));

And get back an array containing 182, 66, 24, and 45. Of course, if any of the individual strings would throw a NumberFormatException, parseInts will too.

CodePudding user response:

As Scott Hunter mentioned in comments, you might need to do following inside main:

public static void main(String[] args){
        Scanner ip = new Scanner(System.in);
        System.out.println("Enter in the ip.");
        String ipstr = ip.nextLine();
         for (String string : ipstr.split("[.]")) {
                convertbinary(Integer.parseInt(string));
            }
    }
  •  Tags:  
  • java
  • Related