Issue
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);
}
Solution
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));
}
}
Answered By - Ashish Patil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.