Issue
I'm trying do a code where transform a String into a "Dancing string". My code are working but I want ignore spaces " ", how can I do it?
Example:
Output: Dancing sentence: HeLlO GuYs
I want this output: " HeLlO gUyS"
import java.util.Scanner;
public class Main {
String retorno="";
Main(){
}
String concatena(String frase){
String[] split = frase.split("");
for(int i =0; i<split.length;i++){
if(i%2==0){
retorno +=split[i].toUpperCase();
}
else
retorno +=split[i].toLowerCase();
}
return retorno;
}
public static void main(String[] args) {
Main teste = new Main();
System.out.println("Write the dancing sentence: \n");
Scanner scanner = new Scanner(System.in);
teste.concatena(scanner.nextLine());
System.out.println("Dancing sentence: "+teste.retorno);
}
}
Solution
(i%2==0)
doesn't have a way of considering a space on subsequent iterations, so could introduce a boolean and do something like this:
boolean toUpper = true;
for(int i =0; i<split.length;i++){
if(split[i].equals(" ")) {
retorno += split[i];
} else if (toUpper) {
retorno +=split[i].toUpperCase();
toUpper = false;
} else {
retorno +=split[i].toLowerCase();
toUpper = true;
}
}
Answered By - Andrew S
Answer Checked By - Cary Denson (JavaFixing Admin)