0

Java program to accept a string and count total numeric values.

public class Test2{
    public static void main(String[] args){
        String str = "I was 2 years old in 2002";

        int count = 0, i;
        for(i = 0; i < str.length(); i++){
            if(str.charAt(i) >= 48 && str.charAt(i) <= 57){
                count++;
                // while(str.charAt(i) >= 48 && str.charAt(i) <= 57)
                //  i++;
            }
        }

        System.out.println("Output: " +count);
    }
}

Output = 5 After uncommenting the two lines written inside while loop -

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
        at java.base/java.lang.String.charAt(String.java:712)
        at Test2.main(Test2.java:9)

The output should be 2, because there are two numeric values - 2 and 2002 I have commented on the two lines in the above code, after uncommenting the code, the same logic works perfectly in C++.

You can check my C++ code here

pradeexsu
  • 1,029
  • 1
  • 10
  • 27
  • 1
    Add a length check: `while (i < str.length && str.charAt(i) >= 48 && str.charAt(i) <= 57)`. Otherwise, you will always end up with an exception if having a number at the end of the input string. – Seelenvirtuose Dec 30 '20 at 12:14

6 Answers6

5

An alternative to @DarkMatter´s answer using Pattern:

public static void main(String[] args) {
    String str = "I was 2 years old in 2002";
    long count = Pattern.compile("\\d+").matcher(str).results().count();
    System.out.println(count);
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

You are checking individual charters so it counts every digit (as you probably realize). Java String has some nice tools to help you here. You could split the line into words and check each against a regular expression using String.matches():

String str = "I was 2 years old in 2002";

int count = 0;
for(String s : str.split(" ")) {
    if(s.matches("[0-9]*")) {
        count++;
    }
}
System.out.println(count);

You can do the same thing (almost) with a stream:

String str = "I was 2 years old in 2002";

long count = Arrays.stream(str.split(" "))
        .filter(s -> s.matches("[0-9]*")).count();

System.out.println(count);
DarkMatter
  • 1,007
  • 7
  • 13
0

There are many options in Java as already shared by others. Below is very similar to your existing code and gives your desired output:

public static void main(String[] args) {
    String str = "I was 2 years old in 2002";
    String[] splittedString = str.split(" ");

    int count = 0, i;
    for (i = 0; i < splittedString.length; i++) {

        if (StringUtils.isNumeric(splittedString[i])) {
            count++;
        }
    }

    System.out.println("Output: " + count);
}
Community
  • 1
  • 1
NewBee
  • 228
  • 4
  • 14
0

In C, strings end in an ASCII NUL character (well, in basic C, strings don't exist, it's a library bolt-on, but most bolt-ons have NUL terminated strings). In java, that's not how it works.

The reason that your code is not working in java, but it is in C, is that you just keep going until you hit a non-digit character in that inner while loop. That means if the string ends in a digit (which yours does), your code asks the string: Give me the character at (one position beyond its length). In C that works; that's ASCII NUL, and thus your inner loop ends, as that's not a digit.

In java it doesn't, because you can't ask for a character beyond the end of a string.

You can 'fix' your code as pasted by also adding a check that i is still below length: if (i < str.length() && str.charAt(i).... ).

As the other answers showed you, there are more java idiomatic ways to solve this problem too, and probably the strategies shown in the other answers is what your average java coder would most likely do if faced with this problem. But there's nothing particularly wrong with your C-esque solution, once you add the 'check length' fix.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

below code will input String from user and return the number of occurrences of numeric values as count.

import java.util.Scanner;

public class NumberCountingString 
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();

        int count = 0, i;
        int size = str.length(); // will only get size once instead of using in loop which will always get size before comparing
        for(i = 0; i < size; i++)
        {
            if(Character.isDigit(str.charAt(i))) //if char is digit count++
            {
                count++;
                for (int j = i; j < size; ) //inner loop to check if next characters are also digits 
                {
                    if(Character.isDigit(str.charAt(j))) // if yes skip next char
                    {
                        i++;
                        j=i;
                    }
                    else{ //break inner loop 
                        break;
                    }
                }
            }
        }

        System.out.println("Output: " +count);
    }
}
0

You can split this string into an array of words, then filter those words where codePoints of the characters match digits, i. e. allMatch (Character::isDigit), and count these words:

String str = "I was 2 years old in 2002";

long count = Arrays
        // split string into an array of words
        .stream(str.split("\\s+"))
        // for each word check the code points of the
        // characters, whether they are digits or not.
        .filter(w -> w.codePoints()
                .mapToObj(ch -> (char) ch)
                .allMatch(Character::isDigit))
        .count();

System.out.println(count); // 2

See also: Transform String to byte then to int