Method call within a class

Asked

Viewed 73 times

2

I have this part of my code where I call a class to add '0' to a character group that must have 4 characters.

StringTokenizer frase = new StringTokenizer(IMEIstring,".");
String first = frase.nextToken();
if(first.length()<4){
    AddOh instancia = new AddOh();
    String primeiro = instancia.AddZero(first);
    first = primeiro;
}

However it does not call the class, it gives error. In Logcat nothing appears and when I do Debug is as the following: inserir a descrição da imagem aqui

Below the complete code of the class Addoh: (Ah, if I put it inside the main class as an internal function and try to call it without instance also does not run)

package com.example.minhaslicencasnobre;

public class AddOh {
    public String AddZero(String pedaco) {
        String fim = null;
        String[] H = null, finish, temp;
        int i,j=0;

        finish = new String[4];
        temp = new String[4];

        if(pedaco.length()<4){
            int tam =  pedaco.length();

            for(i=0;i<pedaco.length();i++)
                H[i] = pedaco.substring(i, i+1);

            for(i=3;i>=0;i--){
                if(i<tam){
                    temp[i]= H[j];
                    j++;
                }else
                    temp[i]="0";    
            }
            j=temp.length-1;
            for(i=0;i<temp.length;i++){
                finish[i] = temp[j];
                j--; 
            }
        }
        for(i=0;i<=finish.length;i++){
            fim = fim + finish[i];
        }
        return fim;
    }
}
  • Just to understand: do you have any string and want it to be completed with zeros on the right? As if you had A2 and come back A200?

  • @Paulorodrigues it would return as 00A2. In the method has a part that comes back as A200 but then is put correctly as 00A2.

  • Is it possible that string contains space? If not, I believe it can be done differently instead of all this code.

  • No @Paulorodrigues has to be only the 4 characters.

1 answer

2


From what I understand of your question and according to the comments, I believe that the solution can be well simplified using the class itself String.

Try something like that:

first = String.format("%4s", first).replace(' ', '0')

So you’ll have one "padding" left on her string and then replaced by zeroes each space.

See an example on Ideone.

  • Gosh, I got so much for the solution to be as simple as that Thank you @Paulorodrigues

Browser other questions tagged

You are not signed in. Login or sign up in order to post.