java - 如何检查字符串是否为数字

标签 java arrays hashmap

<分区>

我在 Core Java 中有转换到 Map 的问题。

要求如下:
给定下面的字符串数组

String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};          

将其转换为 Map,使得结果输出如下

输出

======      ======         
key         Value        
======      ======                  
abc          true       
123          false       
def          true      
456          false

The above should be printed for each element in the array. I have written the code but it's not working and I'm stuck. Please let me know how it can be resolved. Thanks in advance.

import java.util.HashMap;       
import java.util.Iterator;       
import java.util.Map;       

public class CoversionToMap {

/**
 * @param args
 */
public static void main(String[] args) {
    String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};
    Map m = new HashMap();
    for(int i=0;i<str.length;i++){
        if(Integer.parseInt(str[i]) < 0){
            m.put(str[i],true);
        }else{
            m.put(str[i],false);
        }
    }
    //Print the map values finally
    printMap(m);
}   

public static void printMap(Map mp) {
        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry)it.next();          
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
        }
}  
}           

异常(exception):

Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"       
    at java.lang.NumberFormatException.forInputString(Unknown Source)       
    at java.lang.Integer.parseInt(Unknown Source)       
    at java.lang.Integer.parseInt(Unknown Source)       
    at CoversionToMap.main(CoversionToMap.java:22)       

最佳答案

每个人都建议为此使用异常处理,这里没有什么特别之处可以保证使用这样的异常,你不要尝试在你的车里左转,如果你撞了就往右转,对吗?像这样的事情应该做到这一点

Map<String, Boolean> m = new HashMap<String, Boolean>();
for (String str: strs) {
    m.put(str, isInteger(str));
}

public boolean isInteger(String str) {
    int size = str.length();

    for (int i = 0; i < size; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }

    return size > 0;
}

比捕获抛出的异常更清晰、更高效,即使有 99% 的整数,因为甚至不需要整数值,因此不需要转换。

关于java - 如何检查字符串是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597485/

相关文章:

java - 所有声明为类变量的数组都应该是静态的吗?

c++ - const 指针和 const 数组的输出

java - 从原始值键值对 hashmap Java 中获取键值对

java - C#语言等同于ScheduledExecutorService

java - JAXB:获取错误 "Cannot resolve the name xxx to a(n) ' 类型定义'组件。”

c# - 逐行读取 .txt 文件,识别特定字符

java - 使用 HashMap 对相似的项目进行分组

java - 为什么在 `HashMap Class` 中的哈希函数中使用 4,20,12,7 这样的数字

java - 在 HttpSessionListener 中如何获取 HttpServletRequest?

java - @RequestParam 为空(Spring MVC)