(CoderByte) Number Search - Solução

Using the Java language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number. For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single digit numbers and multiple digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol.

Solução:

import java.util.*;
import java.io.*;
import java.lang.*;

class Function {
  int NumberAddition(String str) {
    String numeros = "";
    boolean apareceuNumero = false;
    for (int i = 0; i < str.length(); i++) {
      if (Character.isDigit(str.charAt(i))) {
          numeros += str.charAt(i);
        apareceuNumero = true;
      }
      else if (!Character.isDigit(str.charAt(i)) && apareceuNumero == true) {
          numeros += " ";
        apareceuNumero = false;
      }
    }

    if (numeros.length() > 0) {
      String[] numerosSeparados = numeros.split(" ");

      int soma = 0;
      for (int i = 0; i < numerosSeparados.length; i++) {
          soma += Integer.parseInt(numerosSeparados[i]);
      }

      return soma;
    }
    else {
        return 0;
    }
  }
  public static void main (String[] args) {
    // keep this function call here   
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.NumberAddition(s.nextLine()));
  } 
 
}         

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução