Results 1 to 2 of 2
  1. #1
    jgg
    jgg is offline Member
    Join Date
    Feb 2011
    Location
    Glasgow
    Posts
    2
    Rep Power
    0

    Default Scanner Class Problem

    I'm trying to use the Scanner class to convert a string into the equivalent bytes. So something like
    10 1a 9f
    will become
    16
    26
    47
    I've tried using the following code which works fine up to a point...
    Java Code:
    package scanner;
    
    import java.io.*;
    import java.util.Scanner;
    /**
     *
     * @author sc31jg
     */
    public class ParseString {
        /**
         * @param args the command line arguments
         */
        public static void main(String... aArgs) throws FileNotFoundException {
            String input = "10 1a 9f";
            Scanner s = new Scanner(input).useDelimiter("\\s").useRadix(16);
            try {
                while (s.hasNextByte()) {
                    System.out.println(s.nextByte());
                }
            }
            finally{
                s.close();
            }
        }
    }
    The problem happens when the input string is changed to any string higher than 7f, so
    10 1a 7f
    returns
    16
    26
    127
    but
    10 1a 80
    returns
    16
    26
    How do I get the strings 80 to ff converted?

  2. #2
    jgg
    jgg is offline Member
    Join Date
    Feb 2011
    Location
    Glasgow
    Posts
    2
    Rep Power
    0

    Default

    Fixed by using Integer.parseInt as follows..

    Java Code:
    package scanner;
    
    public class HexStringToInt {
    
        public static void stringToInt(String base) {
            // split the input on space into a string array
            String [] splitString = base.split("\\s");
    
            // parse each entry to an integer
            for (int i = 0; i < splitString.length; i++) {
                int intValue = Integer.parseInt(splitString[i],16);
                System.out.printf("%d ", intValue);
            }
        }
        public static void main(String[] args) {
            String s = "00 20 a1 ff";
            System.out.println(s);
            stringToInt(s);
        }
    }
    but why does the Scanner method not work?

Similar Threads

  1. scanner Class
    By vibaviattigala in forum New To Java
    Replies: 2
    Last Post: 11-30-2010, 07:31 PM
  2. Using Scanner class in GUI
    By Indegon in forum New To Java
    Replies: 13
    Last Post: 11-12-2010, 10:50 PM
  3. Using the scanner class
    By danielwestjr in forum New To Java
    Replies: 1
    Last Post: 03-13-2009, 10:49 AM
  4. Scanner class
    By ajaymenon.k in forum Advanced Java
    Replies: 1
    Last Post: 11-26-2007, 07:01 AM
  5. problem with scanner class:incompatible types
    By fred in forum New To Java
    Replies: 1
    Last Post: 07-20-2007, 07:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •