问题描述:

Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...

The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.

I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.

*********UPDATE************************

So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY

Which is progress but I can't understand why it's repeating those first characters so many times??

I edited the code too.

*********UPDATE*****************************

public class ThreeLetterAcronym {

public static void main(String[] args) {

String threeWords;

StringBuilder acronym = new StringBuilder();

Scanner scan = new Scanner(System.in);

System.out.println("Enter your three words: ");

threeWords = scan.nextLine();

for(int count = 0; count < threeWords.length(); count++) {

acronym.append(threeWords.charAt(0));

if(threeWords.charAt(count) == ' ') {

++count;

acronym.append(threeWords.charAt(count));

}

}

System.out.println("The acronym of the three words you entered is: " + acronym);

}

}

网友答案:

You can't save the other characters because char is supposed to store only one character. You can use a StringBuilder in this case

  StringBuilder acronym = new StringBuilder();

Then in your loop simply replace it with

       String[] threeWordsArray = threeWords.split(" ");

        for(String word : threeWordsArray) {
            acronym.append( word.substring(0, 1) );
        }

**updated

网友答案:

You store the character at the current index in space:

char space = threeWords.charAt(count);

Then you compare the value of space with the integer value 3:

if(space < 3)

This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.

相关阅读:
Top