Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Convert String to Int without using parseInt?

    I am having difficulty converting any string to a int.The string has letters so parse int will not work...besides i cant use it anyway. I was thinking using Ascii codes to get letters out, but even that, how do you convert a string of numbers to a single int???

    Code:
    public static void main(String[] args)throws Exception {
             String t = "abc435"
    
             int num = 0;
    
             num = parse(t);
            
             System.out.println("num = " + num );        
                  
        }
    public static int parse(String s )throws Exception{
         
              int k=1;
            if( s.equals("")){
                  k = 0;
                }
            else{
                for( int i=0;i<s.length();i++){
                    char letter = s.charAt(i);
                         if(((int)letter >= 48)&&((int)letter <= 57)){
                             System.out.print(letter);
                            
                        }
                         else{
                         
                             System.out.println(s);
                             
                        continue;
                         }
                     
                }
            }
            System.out.println("");
           
               
           return k;
        }

  • #2
    Regular Coder cs_student's Avatar
    Join Date
    Oct 2009
    Location
    ~/
    Posts
    195
    Thanks
    2
    Thanked 22 Times in 22 Posts
    First you should learn to format your code so that it is readable. If you don't already have a personal preference you should try to stick to the standards given in the pdf about Java Coding Conventions.

    As for how you could go about converting a sting to an integer, you could to it by casting it to an integer if it is indeed an integer, then forming the string.

    I can't be completely sure because you are vague about the parameters of the problem. You say there could be letters within the string, so I'm not sure how you are supposed to know which numerals go together to form numbers and which do not.

    Let's suppose you have a string such as "4a5b6c7" and what you are trying to get is the integer 4567.

    In this case you could do something similar to what you did in the parse method. Loop through every char in the string and see if it is a number or a letter.
    Now I assume the problem is that you don't know how to get the integers, 4, 5, 6, and 7 to turn into 4567.

    What you could do is have an integer that you multiply by ten everytime a new integer is found in the string, then add the new integer. ie if you had the variable int buffer = 0; You would first come across 4. You would do 0*10=0. Then add 4. Then you would come across 5. You would do 4*10=40. Then add 5 to get 45. Just continue this process.

    Hope that helps

  • #3
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up


    I am new to the forums..but the instructions was to parse a String to an Int. If the String was "abc123" return 123 as a int. if "a1b2c3" retrun 123.

    I actually used your advice and got this:
    *sorry bout the format
    Code:
     public static int parse(String s )throws Exception{
                int digitvalue = 0;
                int power =0;
                int newInt = 0;
                String tempString = null;
                String FinalString = null;
            
                tempString = (s.replaceAll("[a-zA-Z]",""));
                FinalString = removeSpaces(tempString);
                power =FinalString.length()-1;
                  for( int i=0;i<FinalString.length();i++){
                    char letter = FinalString.charAt(i);
                  
                               digitvalue = Character.digit(letter, 10);
                             
                               newInt = newInt + (digitvalue*(int)Math.pow(10,power));
                                 
                                  power--;
                      }  
                 
          return newInt ;
        }

  • #4
    Regular Coder cs_student's Avatar
    Join Date
    Oct 2009
    Location
    ~/
    Posts
    195
    Thanks
    2
    Thanked 22 Times in 22 Posts
    I was thinking of something more along the lines of
    Code:
            String str = "abc123";
            int value = 0;
            for(int i = 0; i < str.length(); i++) {
                int current = ( (int) str.charAt(i) ) - 48;
                if(current >= 0 && current <= 9) {
                    value *= 10;
                    value += current;
                }
            }
            System.out.println(value);

  • #5
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Full Solution

    Exception class

    NonDigitFound.java


    Code:
    public class NonDigitFound extends Throwable {
    
        public char ch;
    
        public NonDigitFound() {
            ch = '-';
        }
    
        public NonDigitFound(char c) {
            ch = c;
        }
    
        //prints exception causing char
        public void cause() {
            System.out.println("NonDigitFound thrown : CAUSE '" + ch + "'");
        }
    }

    Class with parseInt method

    parseIntMe.java


    Code:
    public class parseIntMe {
    
        public static void main(String[] args) {
       try {
                System.out.println(intParse("1234.56789"));
            } catch (NonDigitFound ex) {
                ex.cause();
            }
        }
    
        private static int intParse(String x) throws NonDigitFound {
    
            //empty string return 0
            if (x.isEmpty()) {
                return 0;
            }
    
            char ch;
            int n = 0;
            int flag = 0;
            int len = x.length();
    
    
            //check decimal presence
            if (x.contains(".")) {
                len = x.indexOf('.');
            }
    
            //check - or + presence
            if (x.charAt(0) == '-' || x.charAt(0) == '+') {
                flag = 1;
            }
    
            for (int i = flag; i < len; i++) {
                ch = x.charAt(i);
    
                //done parsing till '.' exclusive, now break.
                if (ch == '.') {
                    break;
                }
    
    
                //15 = 1 * (10 RaiseToPower 1) + 5 * (10 RaiseToPower 0) = 10 + 5 = 15
                if ((int) ch >= 48 && (int) ch <= 59) {
                    n += (((int) ch - 48) * ((int) Math.pow(10, len - i - 1)));
    
                } else {
                    //found a non digit
                    throw new NonDigitFound(ch);
                }
            }
    
            //- or + was found
            if (flag == 1) {
                switch (x.charAt(0)) {
                    case '-':
                        return 0 - n;
                    case '+':
                        return n;
                }
            }
            return n;
        }
    }

    Output

    1234


    Download Source
    http://www.mediafire.com/?pvuxbg7ivebgidv
    .....
    Last edited by parrygill; 02-10-2011 at 02:43 AM.


  •  

    Tags for this Thread

    Posting Permissions

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