(Java refers to offer) a string representing a value

1. Question analysis

Please implement a function to determine whether a string represents a value (including integers and decimals).

For example, the string "+100","5e2","-123","3.1416"and "-1E-16"both represent numeric values.
However, "12e","1a3.14","1.2.3","+-5"and "12e+4.3"not.

The key to this question is right + - . e E, the discussion of these 5 characters

(1) e/E cannot appear twice at the same time, and must be followed by a number.
(2) The positive and negative sign, if it appears for the first time, either the position is at the beginning or immediately after e/E, if it is the second The second occurrence must immediately follow e/E.
(3) The decimal point cannot appear twice and cannot appear after e/E

Second, the code

import java.util.Arrays;
import java.util.Scanner;

/**
 * @Auther: Yolo
 * @Date: 2020/9/11 16:58
 * @Description:
 */
public class Test_11 {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入字符串:");
        String next = scanner.next();
        char[] str = next.toCharArray();
        System.out.println(Arrays.toString(str));
        boolean result = isNumeric(str);
        System.out.println(result);
    }

    //e的ascii:101,
    private static boolean isNumeric(char[] str) {
    
    
        //标记符号,小数点,e是否出现过
        boolean sign = false, decimal = false, hasE = false;

        for (int i = 0; i < str.length; i++) {
    
    
            if (str[i] == 'e' || str[i] == 'E') {
    
    
                //e 或 E 的后面一定要接数字,不能是末位出现
                if (i == str.length - 1) {
    
    
                    return false;
                }
                //不能同时存在两个 e/E
                if (hasE) {
    
    
                    return false;
                }
                hasE = true;
            } else if (str[i] == '+' || str[i] == '-') {
    
    
                //第二次出现正负号,必须紧接在 e 之后
                if (sign && str[i - 1] != 'e' && str[i - 1] != 'E') {
    
    
                    return false;
                }
                //第一次出现正负号,如果不是在开头,则也必须紧接在 e之后
                if (!sign && i > 0 && str[i-1] != 'e' && str[i-1] != 'E') {
    
    
                    return false;
                }
                sign = true;
            } else if (str[i] == '.') {
    
    
                //e后面不能接小数点,小数点也不能出现两次
                if (hasE || decimal) {
    
    
                    return false;
                }
                decimal=true;
            } else if (str[i] < '0' || str[i] > '9') {
    
    
                //其余的不合法字符
                return false;
            }
        }
        return true;
    }
}

Three, summary

The key is to mark the E/e, decimal point, and sign in advance to determine the number of occurrences

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108545561