String Input (Only outputs the first word said) - java

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.

Related

How to fix this non-compiling method?

Doing some practice exam questions, and it says to:
assume the statement String pattern = getPattern();. Explain if any flow in the method getPattern(). How would you fix it?
Here's the code:
public static String getPattern() {
Scanner inPattern = new Scanner(System.in);
String pattern = " ";
boolean valid = false;
int i = 0;
while(!valid){
System.out.println("please enter a valid pattern with X or x");
pattern = inPattern.next();
if ( ! (pattern.charAt(i) == 'X' || pattern.charAt(i) == 'x'
|| pattern.charAt(i) == 'r'))
System.out.println("You have entered an invalid pattern");
else if ((i + 1) == pattern.length()) valid = true;
};
inPattern.close();
return pattern;
}
I'm not really sure how I would fix this... obviously this is a smaller part of a bigger code because this doesn't include a main method, personally making it a bit more difficult to see what's wrong.
I'm really not sure exactly what to change here. I've been up for 7+ hours watching youtube videos and attempting to understand this stuff or to do this question but I really cannot figure it out. would anyone be able to provide a good example?
Okey, so first things first. The code you recieved is all you need to run it, its not part of a "bigger program". It tells you to assume its being called like this:
String pattern = getPattern();
So when calling the method "getPattern" from a main method what happens? You get prompted to input a "valid" character, if the character is valid the method returns the character.
The question itself is weirdly designed. But looking at the code, I guess what they're fishing for is that you're being told to input the character 'x' or 'X'. But in the code another valid character is 'r'. So either they want you to change the text given to the user, or remove 'r' as a valid char would be my guess.

I'm having a hard time terminating a java loop

I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}

How do I check see a newline character with my scanner if I'm using a delimiter?

I'm trying to make an undirected graph with some of the nodes (not all, unlike my example) being connected to one another. So my input format will look like
3
1:2,3
2:1,3
3:1,2
Meaning there's three nodes in all, and 1 is connected to 2 and 3, 2 is connected to 1 and 3 and so on.
However, I cannot understand how to take the input in a meaningful way. Here's what I've got so far.
public Graph createGraph() {
Scanner scan = new Scanner(System.in).useDelimiter("[:|,|\\n]");
int graphSize = scan.nextInt();
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
while (!scan.hasNext("\\n")) {
System.out.println("Scanned: " + scan.nextInt());
}
}
return new Graph(graphSize);
}
Can my
while (!scan.hasNext("\\n"))
see the newline character when I'm using a delimiter on it?
In my opinion, you shouldn't be using those delimiters if they are meaningful tokens. In the second line for example, the first integer doesn't have the same meaning as the others, so the : is meaningful and should be scanned, even if only to be discarded later. , however doesn't change the meaning of the tokens that are separated by it, so it's safe to use as a delimiter : you can grab integers as long as they are delimited by ,, they still have the same meaning.
So in conclusion, I would use , as a delimiter and check manually for \nand : so I can adapt my code behaviour when I encounter them.
yup, scanner can definitely detect new line. infact you dont even have to explicitly specify it. just use
scan.hasNextLine()
which essentially keeps going as long as there are lines in your input
Edit
Why dont you read everything first and then use your for loop?
Alright I figured it out. It's not the prettiest code I've ever written, but it gets the job done.
public Graph createGraph() {
Scanner scan = new Scanner(System.in);
number = scan.nextLine();
graphSize = Integer.valueOf(number);
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
number = scan.nextLine();
Scanner reader = new Scanner(number).useDelimiter(",|:");
while (reader.hasNextByte()) {
System.out.println("Scanned: " + reader.nextInt());
}
}
return new Graph(graphSize);
}

Efficent way to replace underscore with char or string

I have researched this topic for a while, but without much success. I did find the StringBuilder and it works wonders, but that's as far as I got. Here is how I got my hangman program to work like it should:
if(strGuess.equalsIgnoreCase("t")){
mainword.replace(0,1,"T");
gletters.append('T');
}
else if(strGuess.equalsIgnoreCase("e")){
mainword.replace(1,2,"E");
gletters.append('E');
}
else if(strGuess.equalsIgnoreCase("c")){
mainword.replace(2,3,"C");
gletters.append('C');
}
else if(strGuess.equalsIgnoreCase("h")){
mainword.replace(3,4,"H");
gletters.append('H');
}
else if(strGuess.equalsIgnoreCase("n")){
mainword.replace(4,5,"N");
gletters.append('N');
}
else if(strGuess.equalsIgnoreCase("o")){
mainword.replace(5,6,"O");
mainword.replace(7,8,"O");
gletters.append('O');
}
else if(strGuess.equalsIgnoreCase("l")){
mainword.replace(6,7,"L");
gletters.append('L');
}
else if(strGuess.equalsIgnoreCase("g")){
mainword.replace(8,9,"G");
gletters.append('G');
}
else if(strGuess.equalsIgnoreCase("y")){
mainword.replace(9,10,"Y");
gletters.append('Y');
}
else{
JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word!");
errors++;
gletters.append(strGuess.toUpperCase());
}
SetMain = mainword.toString();
GuessedLetters = gletters.toString();
WordLabel.setText(SetMain);
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
However, I can't do this for EVERY letter for EVERY word, so is there a simple and efficient way to do this? What I want is to have a loop of some sort so that I would only have to use it once for whatever word. So the word could be technology (like it is above) or apple or pickles or christmas or hello or whatever.
I have tried using a for loop, and I feel the answer lies in that. And if someone could explain the charAt() method and how/where to use it, that'd be good. The closest I got to being more efficient is:
for(i = 0; i < GuessWord.length(); i++) {
if (GuessWord.charAt(i) == guess2) {
mainword.replace(i,i,strGuess.toUpperCase());
}
So if you could use that as a basis and go off of it, like fix it? Or tell me something I haven't thought of.
It's a good question. There's clearly repeated code, so how do you replace all that with something reusable. Actually, you can dispense with all of your code.
That whole code block can be replaced by just one line (that works for every word)!
String word = "TECHNOLOGY"; // This is the word the user must guess
mainword = word.replaceAll("[^" + gletters + "]", "_");
This uses replaceAll() with a regex that means "any letter not already guessed" and replaces it with a underscore character "_". Note that Strings are immutable, and the replaceAll() method returns the modified String - it doesn't modify the String called on.
Here's some test code to show it in action:
public static void main(String[] args) {
String word = "TECHNOLOGY"; // what the user must guess
StringBuilder gletters = new StringBuilder("GOTCHA"); // letters guessed
String mainword = word.replaceAll("[^" + gletters + "]", "_");
System.out.println(mainword);
}
Output:
T_CH_O_OG_

How to read a string with spaces in Java

I am trying to read a user input string which must contain spaces. Right now I'm using:
check = in.nextLine();
position = name.names.indexOf(check);
if (position != -1) {
name.names.get(position);
} else {
System.out.println("Name does not exist");
}
this just returns various errors.
your question isn't very clear - specfically you like like you are checking that what the person has typed matches a known list, not that it does or doesn't have spaces in it, but taking you at your word:
Read the whole line in, then check using
a) Regex
b) indexof() - if your check is very simple
Possibly also want to do a length check on the input line as well (i.e all lines should be < 255 chars or something) , just to be paranoid
If you are doing more like what you code sample looks like then you do something like
ArrayList<String> KnownListOfNames = .....
if(!KnownListOfNames.Contains(UserEnteredString)){
System.out.println("Name not found");
}
Typically you would also do some basic input validation first - google for "SQL injection" if you want to know more.

Categories

Resources