String corresponding to real number

3

I'm trying to check if a String x matches a real number (any). For this I created the following method:

public static boolean Real(String s, int i) {

  boolean resp = false;
  //
  if ( i == s.length() ) {
     resp = true;
  } else if ( s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
     resp = Real(s, i + 1);
  } else {
     resp = false;
  }
  return resp;
}

public static boolean isReal(String s) {

  return Real(s, 0);
}

But obviously this method is only for integers , not real . Could you suggest me how to do this verification?

Q: I can only use the functions: s.charAt(int) and length() of Java.

    
asked by anonymous 01.03.2015 / 01:25

2 answers

1

I suggest adding a parameter to your function, indicating whether you have already found the comma or not:

public static boolean Real(String s, int i, boolean virgula) {
    ...
    else if ( s.charAt(i) == ',' && !virgula ) {
        resp = Real(s, i + 1, true); // Passa virgula pra true
    } else if ( s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
        resp = Real(s, i + 1, virgula); // Repete virgula
    } ...
}

public static boolean isReal(String s) {
    return Real(s, 0, false);
}

It would also be interesting to test for - up front. Since this only happens once (at the beginning of the string), it is better to do in the base case ( isReal(String) ) instead of the recursive function.

    
01.03.2015 / 02:05
1

You can do this, you validate if it is really a number and if it is, if it is a real number.

public static boolean isReal(String s){
    boolean isNumber = false;
    boolean isReal = false;
    for(int x=0; x<s.length(); x++){
        if((s.charAt(x) >= '0' && s.charAt(x) <= '9') || s.charAt(x) == '.'){ //verifico se é um numero e/ou se contem um ponto '.'
            isNumber = true;
            if(s.charAt(x) == '.' && x>0 && x<s.length()-1){ //aqui eu verifico se o ponto nao esta no começo ou no fim da string.
                if(!isReal) //se o numero ja tiver sido validado como real, ele ja tem um ponto, se tiver outro nao é um numero valido
                    isReal = true;
                else
                    return false;
            }else{
                if(s.charAt(x) == '.') //se for um segundo, ou superior, ponto da string e estiver nas estremidades finaliza.
                    return false;
            }
        }else{
            return false;
        }
    }
    if(isNumber && isReal) //se os dois forem verdade entao é a string é um numero este numero é real.
        return true;
    else
    return false;
}

As you can see I checked if it is a number, checking if each character is between 0 and 9 or if it is a '.', if it is within the parameters it is a real number. There can be no more than one point to be a valid number and the points can not be at the ends of the string.

    
03.03.2015 / 06:13