Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a number [duplicate]

I have conversion to Map problem in Core Java.

Below is requirement:
Given a String array below

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

Convert it into a Map such that the resultant output is below

Output

======      ======         
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)       
like image 940
Deepak Avatar asked Sep 29 '11 12:09

Deepak


People also ask

How do you find duplicates in a string python?

Take a string input using the input() function. Declare an empty list called dups. Iterate through the string using a for loop, using the . count() function check if the occurrence of a character is more than one in the giver string, if true, append it to the dups list.

How do you find duplicate characters in a string C++?

Algorithm. Define a string and take the string as input form the user. Two loops will be used to find the duplicate characters. Outer loop will be used to select a character and then initialize variable count by 1 its inside the outer loop so that the count is updated to 1 for every new character.


1 Answers

Everyone is suggesting using exception handling for this, there is nothing exceptional here to warrant using exceptions like this, you don't try turning left in your car and if you crash go right do you? Something like this should do it

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;
}

Much clearer and more efficient that catching throwing exception, even when there are 99% integers as the integer value is not even needed so no conversion required.

like image 64
vickirk Avatar answered Sep 23 '22 10:09

vickirk