String to int type, do not use the methods in the library

A problem I encountered.
Integer.parseInt (String str); This method does not deal with the space removal of the string, String.trim (); The method can only remove the first and last spaces,
so I wrote a corresponding method, there is something wrong, hope you Great God's guidance.

To convert String to int, use the library method Integer.parseInt (String); using this library method, you will find that this method has some defects and does not deal with spaces. (The following points should be noted for the self-writing method)
1. Determine whether the string is empty or null.
2. Boundary limitation, int type (-2 ^ 16-2 ^ 16-1). Here is a knowledge point, when Integer.MAX_VALUE + 1, the result is equal to Interger.MIN_VALUE. The reason is that the data is stored in binary. The maximum value of int is 0 1111 1111 1111 1111, a total of 16 bits. When it is increased by 1, it becomes 1 0000 0000 0000 0000. The first 0 is a positive number and 1 is a negative number.
Added:
general computer
has the original code number of symbols, complement, anti-code the first bit is 0 for positive, 1 for negative.
If it is an unsigned number, it does not mean a sign, but also as a data bit.
If it is a code shift, the first digit is 0 for negative numbers and 1 for positive numbers.
3. Remove the spaces in the character string and remove all spaces.
4. Illegal character input. (Nothing is written at the moment, it will be added next time.)

code show as below:

package javaDemo;

import java.util.Scanner;

public final class StringtoInt {

    static int max = Integer.MAX_VALUE;
    static int min = Integer.MIN_VALUE;
    /**
     * 将String字符串转化为int。
     * @param str
     * @return int
     *
     */
    public static final int stringtoint(String str){
        int goalint = 0;
     //判断str是否为null;
     if(str == null || str == ""){
         throw new NumberFormatException("该字符串为null,或''.");
     } else{
         //去空格,这里有tirm()方法,但是其知只是去掉了头和尾的空格:
         // str.trim();
         //不使用类库的方法进行去空格。
        String string = StringtoInt.trim(str);
        char[] arr = string.toCharArray();
        //判断是否为负数。
         int len = arr.length;
        if(arr[0] == '-'){
              for(int i = 1; i < len; i++){
                  goalint += (Character.getNumericValue(arr[i]))*(Math.pow(10,len-i-1));
              }
              if((0-goalint) < min){
                  throw new NumberFormatException("输入数字小于int的最小值。");
              }
              //求其相反数
              goalint = 0 - goalint;
        }else{
            for(int i = 0; i < len; i++){
                //Character.getNumericValue(arr[i])获取的是字符所显示的数字。
                //Integer.parseInt(char ch);获取的也是字符串显示的值。
                //而不是ASCII编码值。
                goalint += (Character.getNumericValue(arr[i]))*(Math.pow(10,len-i-1));
            }
            if(goalint > (max)){
                throw new NumberFormatException("输入数字大于int的最大值。");
            }
        }
     }
     return goalint;
    }

    /**
     * 去掉字符串中所有空格。
     * @param str
     * @return String 去空格后的String
     */
    public static final String trim(String str){
        char[] arr = str.toCharArray();
        StringBuffer stringBuffer = new StringBuffer();
        //ch表示空格。
        char ch = ' ';
        for (int i = 0; i < arr.length; i++) {
           if(arr[i] != ch){
               stringBuffer.append(arr[i]);
           }
        }
        String string=stringBuffer.toString();
        return string;
    }

    public static void main(String []args){
        for(int j = 1; j < 10;j++){
            System.out.println("输入要测试"+j+"的字符串");
            String str = new Scanner(System.in).nextLine();
            int i = stringtoint(str);
            System.out.println(i);
        }
    }
}

Published 26 original articles · praised 0 · visits 9938

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/78681203