Snorrarcisco
Snorrarcisco

Reputation: 83

Struggling with uppercase or lowercase

import java.util.Scanner;

public class ShoutandWhisper {

    public static void main(String[] args) 
    {
        //defining the variables
        String word, word1;
        //Input
        Scanner kb = new Scanner(System.in);
        System.out.print("Give me a word that has 7 letters > ");
        word = kb.nextLine();
        word1 = word.toUpperCase();
        System.out.println("I shout " + word1 + " when I'm excited, but i whisper " + word + " when i can't disturb the neigbours.");
        char achar = word.charAt(0);
        char bchar = word.charAt(1);
        char cchar = word.charAt(2);
        char dchar = word.charAt(3);
        char echar = word.charAt(4);
        char fchar = word.charAt(5);
        char gchar = word.charAt(6);
        //Changing to uppercase
        char Bchar = Character.toUpperCase(bchar);
        char Dchar = Character.toUpperCase(dchar);
        char Fchar = Character.toUpperCase(fchar);
        System.out.println("And the mixed up word is " + achar+Bchar+cchar+Dchar+echar+Fchar+gchar);
    }

}

Now the code does work but is there a shorter way to produce alternating Uppercase or Lowercase outputs without using a For counter? rewriting the entire "newer" variables is an accident waiting to happen. Especially with me.

I tried to force it as i was selecting the letter by letter and I couldn't do it.

Main goal is to either Shout or whisper and then sort the word using alternating Uppercases from second letter.

Upvotes: 2

Views: 531

Answers (2)

AJMansfield
AJMansfield

Reputation: 4129

Here is a possibility:

public static String scrambleCase(String arg){
    StringBuilder b = new StringBuilder(arg.length());

    for(char ch: arg.toCharArray())
        if(b.length() % 2 == 0) b.append(Character.toUpperCase(ch));
        else b.append(Character.toLowerCase(ch));

    return b.toString();
}

Upvotes: 0

Alexis C.
Alexis C.

Reputation: 93842

You can convert the word to an array of char and use a for loop to alternate upper and lower case :

char [] c = word.toLowerCase().toCharArray();

for(int i = 1; i < c.length; i = i+2){
    c[i] = Character.toUpperCase(c[i]);
}

Then just construct a new String with this char array (using the constructor String(char[] value)) and you'll get your word.

Upvotes: 5

Related Questions