1
My teacher asked to make a method that cancels a character in a sentence using the #
cancels the previous character, example:
Entree: PUO#C MIP#NO#AS
Exit: PUC MINAS
However, my code gives error when using the method replace
or replaceAll
to remove and swap for an empty character. Follow my code below:
public void Elimina(String frase) {
for (int j = 0; j<frase.length(); j++) {
if (frase.charAt(j) == '#') {
frase = frase.replace(frase.charAt(j), '');
frase = frase.replace(frase.charAt(j-1), '-');
}
}
System.out.println(frase);
}
OBS:
frase = frase.replace(frase.charAt(j), '');
-> The mistake is this line on ''
.
frase = frase.replace(frase.charAt(j-1), '-');
-> Here is to show that replacing the method works.
Share the code as text (and formatted here in the OS) instead of in image. And also make it clear which error happens. This makes your question more useful to those who research in the future.
– Rafael Tavares
Not only so that other people can search in the future, but it’s because it’s easier for you to post your code as code so that whoever answers can copy and paste this code than to want whoever answers to have to rewrite it all again.
– Victor Stafusa
charAt
returns achar
butreplaceAll
must receiveString
's, then the code doesn’t even compile. That said, why the character in the positionj - 1
is being replaced by-
? It’s not to eliminate him either?– hkotsubo
@hkotsubo https://docs.oracle.com/en/javase/14/docs/api/java.base/java/lang/String.html#replace(char,char) - What does not compile is the
''
.– Victor Stafusa
Ah, I mistook it for
replaceAll
... Our failure– hkotsubo
A number of great reasons not to post photos of codes, errors and logs and instead use text: https://pt.meta.stackoverflow.com/a/7817/3635 -- respect the tips and rules is to respect the site and the community, accept the tips, they are for the good of all. Welcome.
– Guilherme Nascimento
@Rafaeltavares reissued code and the error happens in replace by empty, as shown in the remark.
– Victor Henrique
@hkotsubo, when I put '-' is to show that it works, but when I put '' it doesn’t work, just to highlight the error.
– Victor Henrique
That hadn’t been made clear. Anyway, it was much easier to put the error message that appeared there (whenever it gives error, even more compilation, some message appears somewhere) :-)
– hkotsubo
@hkotsubo .
– Victor Henrique
This is a build error so the error does not occur before compiling, but during :-) And always an error message appears somewhere (in many editors or has a separate console/window that shows errors or vc puts the cursor/mouse over the point that gives error and the message appears)
– hkotsubo