Why number present at last of string remain undetected in the following programme?

Solution for Why number present at last of string remain undetected in the following programme?
is Given Below:

The problem is to identify the largest integer number present in the given string

public class Main {

  public static void main(String[] args) {
    String str = "dream job 100 and 101";
    long res = 0;
    long temp_res = 0;

    for (int i = 0; i < str.length(); i++) {
      int num = str.charAt(i) - '0';
      
      if (num >= 0 && num <= 9) {
        temp_res = temp_res * 10 + num;
        continue;
      }

      res = Math.max(res, temp_res);
      temp_res = 0;
    }

    System.out.println(res);
  }

}

Expected output – 101

But in this code number present at the last of string remains undetected. Here the output is 100, why is that?
If I add any character after the last number then it will give a correct answer.
Please help me to find out the error.

It’s failing because of the continue. It’s preventing the last max comparison from execute. You can change your code like this:

public static void main(String[] args) {
    String str = "dream job 100 and 101";
    long res = 0;
    long temp_res = 0;
    for (int i = 0; i < str.length(); i++) {
        int num = str.charAt(i) - '0';
        if (num >= 0 && num <= 9) {
            temp_res = temp_res * 10 + num;
            res = Math.max(res, temp_res);
            continue;
        }
        temp_res = 0;
    }
    System.out.println(res);
}

Because you multiply per 10 every new int character (you are increasing the base of the number), you should not have any problem.

Your code isn’t working as you are using continue to find whether the next character in your string is digit too, so that you can add that to parse it in. However, as your string has a digit at the end that is why it gets unchecked due to that continue.

Another thing, to be precise, your approach fails to detect the presence of negative number.

I will suggest you to use regular expression to handle this problem. Use java Pattern and Matcher to find out the digits in your string. You can do:

String str = "dream job -100 and 101";
Pattern p = Pattern.compile("[+-]?\d+");
Matcher m = p.matcher(str);
List<Integer> numberList = new ArrayList<>();
while(m.find()){
    int num = Integer.parseInt(m.group());
    numberList.add(num);
}
System.out.println(Collections.max(numberList));

I’m not the format of your string but you could just splint the string on space and take the last segment.

        String main = "dream job 100 and 101";
        String[] segments = main.split("\s+");
        System.out.println(segments[segments.length - 1]);