Java: charAt convert to int?

前端 未结 6 1183
粉色の甜心
粉色の甜心 2020-12-20 14:39

I would like to key in my nirc number e.g. S1234567I and then put 1234567 individualy as a integer as indiv1 as cha

6条回答
  •  孤城傲影
    2020-12-20 15:09

    I know question is about char to int but this worth mentioning because there is negative in char too ))

    From JavaHungry you must note the negative numbers for integer if you dont wana use Character.

    Converting String to Integer : Pseudo Code

       1.   Start number at 0
    
       2.   If the first character is '-'
                       Set the negative flag
                       Start scanning with the next character
              For each character in the string  
                       Multiply number by 10
                       Add( digit number - '0' ) to number
                If  negative flag set
                        Negate number
                        Return number
    

    public class StringtoInt {

    public static void main (String args[])
    {
        String  convertingString="123456";
        System.out.println("String Before Conversion :  "+ convertingString);
        int output=    stringToint( convertingString );
        System.out.println("");
        System.out.println("");
        System.out.println("int value as output "+ output);
        System.out.println("");
    }
    
    
    
    
      public static int stringToint( String str ){
            int i = 0, number = 0;
            boolean isNegative = false;
            int len = str.length();
            if( str.charAt(0) == '-' ){
                isNegative = true;
                i = 1;
            }
            while( i < len ){
                number *= 10;
                number += ( str.charAt(i++) - '0' );
            }
            if( isNegative )
            number = -number;
            return number;
        }   
    }
    

提交回复
热议问题