简体   繁体   中英

String Input (Only outputs the first word said)

I'm trying to make a piece of code that will yell out anything I input.

So the command is 'yell'

I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.

Here's the piece of code, I hope you can help.

case "npcyell":
    for (NPC n : World.getNPCs()) {
        if (n != null && Utils.getDistance(player, n) < 9) {
            String sentence = "";
            for (int i = 1; i < cmd.length; i++) {
                sentence = sentence + " " + cmd[i];
            }
            n.setNextForceTalk(new ForceTalk("[Alert] "
                    + Utils.getFormatedMessage(sentence)));
        }
    }
    return true;

Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to
text = textInputArea.getText().toString();
and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));

Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
    System.out.println(text.substring(6,text.length() - 1));
}

I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM