Home > Software engineering >  How to check if a string is only number values
How to check if a string is only number values

Time:09-04

I am trying to run a recursion function where i check each character in the string to see if the character is a numeric number, however im a little stuck as the function runs and only checks the first character of the string

public static boolean isNumeric(String str) {

    if(str == null)
    {
        return false;
    }
    if(str=="") {
        return true;
    }

    char first = str.charAt(0);

    if(Character.isDigit(first))
    {
        return true;
    }
    if(Character.isDigit(first) == false)
    {
        return false;
    }


    String reduced = str.substring(1);
    return isNumeric((reduced)); }

CodePudding user response:

Remove below block of code. So that it won't stop at the first character if it is not numeric. This will allow you to keep calling the function if it's still numeric.

if(Character.isDigit(first))
    {
        return true;
    }

CodePudding user response:

Not 100% sure if I understood you correctly. If you want to check, if the string contains numeric values just see my other examples further down. Otherwise, if you want to check, if the string contains exclusively numerical signs and digits you could do something like:

    public static boolean isInteger(String numericValue) {
        if (numericValue == null) return false;
        try {
            Integer.parseInt(numericValue);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

Please note, that this example does only work for Integers. If you want to use bigger numbers, we can use Long or even BigDecimal instead. But the main idea stays the same - check, if it can be parsed.

Or probably more appealing:

    public static void main(String args[]) {
        System.out.println(MyClass.isNumeric(""));
        System.out.println(MyClass.isNumeric(null));
        System.out.println(MyClass.isNumeric("abc"));
        System.out.println(MyClass.isNumeric("a2b"));
        System.out.println(MyClass.isNumeric("1a2b3"));
        System.out.println(MyClass.isNumeric("42"));
        System.out.println(MyClass.isNumeric("-100"));
    }
    
    public static boolean isNumeric(String str) {
        if (str == null) return false; // handle null-pointer
        if (str.length() == 0) return false; // handle empty strings
        // to make sure that the input is numeric, we have to go through the characters
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) return false; // we found a non-digit character so we can early return
        }
        return true;
    }

This will only print true for 42. The other examples contain other characters, too.

There are multiple issues with your code:

    if(str=="") {
        return true;
    }

For string comparison you should use the String.equals() method - there are alternatives to that for example for your use-case you could use the convenience method String.isEmpty() or you could also just check the length of the string.

 if(Character.isDigit(first))
    {
        return true;
    }
    if(Character.isDigit(first) == false)
    {
        return false;
    }

This is some kind of if-else structure here. No need to check the same condition twice. Besides, it won't work with your recursive approach, because for what you want to achieve you need the current state which is "have I already found a digit". You could solve that with a memoized recursive function where you pass the current state along as a second argument to each subsequent call.

In your case it will return the result of the latest iteration / the latest character.

You could do something like the following instead of using recursion. Recursion is fine, but it also comes with some costs. For example is it arguably harder to read and maintain.

    public static void main() { ... } // same as above
    
    public static boolean isNumeric(String str) {
        if (str == null) return false; // handle null-pointer
        if (str.length() == 0) return false; // handle empty strings
        boolean atLeastOneDigit = false;
        // to make sure that the input is numeric, we have to go through the characters
        // until we find the first one then we can early return
        for (char c : str.toCharArray()) {
            if (Character.isDigit(c)) {
                atLeastOneDigit = true; // we found a digit, therefore it must be numeric
                break; // early return to save some iterations
            }
        }
        return atLeastOneDigit;
    }

The output of the program is:

false
false
false
true
true
true
true

Another alternative is to use Regex:

    private static final Pattern digitRegex = Pattern.compile("\\d ");

    public static main() { ... } // same as above

    public static boolean isNumeric(String str) {
        if (str == null) return false;
        Matcher matcher = MyClass.digitRegex.matcher(str);
        return matcher.find();
    }

CodePudding user response:

I am trying to explain you to solve this problem by two string methods that is isDigit(character) and charAt(i). In this case we will try to solve this problem by for loop. we will apply for loop in order to check every character of a string whether it is digit or not. If it is digit we will return true otherwise false.

Code is looks like this :

import java.lang.*;
import java.util.Scanner;
class Main {
public boolean containsDigit(String str) {
    byte flag = 0;
    for (int i = 0; i < str.length(); i  ) {
        if (Character.isDigit(str.charAt(i))) {
            flag = 1;
        }
    }
    if (flag == 1) {
        return true;
    } else {
        return false;
    }
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
    System.out.print("Enter a string : ");
String str = sc.nextLine();
    Main test = new Main();
    boolean chkDigit = test.containsDigit(str);
    if (chkDigit == true) {
        System.out.println("String contains digit.");
    } else {
        System.out.println("String doesn't contain any digit.");
    }
}
}
  • Related