tags:

views:

35

answers:

3

This program takes string like that 192.168.1.125 and cut every number then converts it to integer, but it returns an error.

import java.lang.String;
import java.lang.Number;
import java.lang.Integer;
class Ip
{
   public static void main ( String [] args )
   {

      int i ;
      i = args[0].indexOf ( '.' );
      do
      {
         if ( i != -1 )
            args[0].substring ( 0, i );
         String str = args[0].substring ( i + 1, args[0].length() );
         String str2 = Integer.parseInt ( str );
         System.out.println ( str2 );
      }
      while ( i != -1 );
   }
}
+1  A: 

Integer.parseInt returns an integer, not a string (it's entire point is to create an integer):

String str2 = Integer.parseInt ( str );

Note, the compiler gave an error and you should have tried to figure out what it tells you:

Ip.java:16: incompatible types
found   : int
required: java.lang.String
         String str2 = Integer.parseInt ( str );
R Samuel Klatchko
A: 

You're discarding the result of the first substring, and assigning an integer to a string (as noted by Klatchko). Also, you can simplify if you use a for loop, since IPv4 addresses always have 4 components. This assumes you can't use String.split or similar.

Matthew Flaschen
+1  A: 

On parseInt

parseInt takes a String and returns an int. Here's a simple example of using the method:

    int num = Integer.parseInt("42");
    System.out.println(num == 42); // prints "true"

API references

  • int parseInt(String s)
    • Parameters: s - a String containing the int representation to be parsed
    • Returns: the integer value represented by the argument in decimal.

As for your problem, the simplest solution is to use a java.util.Scanner

     import java.util.*;
     //...

     Scanner sc = new Scanner("192.168.1.125").useDelimiter("\\.");
     int[] parts = new int[] {
         sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()
     };
     System.out.println(Arrays.toString(parts));
     // prints "[192, 168, 1, 125]"

The only non-straightforward part of this is the \\., which is how you write \. as a String literal in Java. The reason why you need the \ is because useDelimiter takes a regex, and in regex dot . is a metacharacter, so you need to escape it to match a literal dot.

API references

See also

polygenelubricants