Reputation: 97
So I am trying to check strings using an if statement,I created like a test computer which gives predetermined responses depending on the input, the only inputs which are working happen to be hi or hello, strings with spaces do not seem to work, why is that?
import java.util.Scanner;
public class ComputaBot {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String text;
String computer = "ComputaBot:";
String[] input = {
"how are you?", "hi", "hello", "what is your name",
"do you like chicken?", "where are you from?",
"do you like cheese?"
};
do{
System.out.println("Type to talk!:");
text = scan.next();
if (text.equals(input[1]) || text.equals(input[2])) {
System.out.println(computer + " " +"Hello!");
}else if (text.equalsIgnoreCase(input[0])) {
System.out.println(computer + " " +"I'm fine, you?!");
}else if (text.equals(input[3])) {
System.out.println(computer + " " +"Jimmy");
}else if (text.equals(input[4])) {
System.out.println(computer + " " +"Yes! Love it");
}else if (text.equals(input[5])){
System.out.println(computer + " " +"Germany");
}else if (text.equals(input[6])){
System.out.println(computer + " " +"only on pizza");
}else
System.out.println("bye");
}while(!text.equals("bye"));
scan.close();
}
}
Upvotes: 2
Views: 80
Reputation: 473
Scan.next() only read in the next word, you want scan.nextLine() for the complete line. It would be better if you use Map add all questions/answers as pair so that you don't have to do all that if/then/else statements.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ComputaBot {
public ComputaBot() {
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String text;
String computer = "ComputaBot:";
Map<String,String> bot = new HashMap<String,String>();
bot.put("how are you?", "I'm fine, you?!");
bot.put("how are you?", "Hello!");
bot.put("hi", "Hello!");
bot.put("what is your name", "Jimmy");
bot.put("do you like chicken?", "Yes! Love it");
bot.put("where are you from?", "Germany");
bot.put("do you like cheese?", "only on pizza");
do {
System.out.println("Type to talk!:");
text = scan.nextLine();
String answer = bot.get(text.toLowerCase());
System.out.println(computer + " " + answer);
} while (!text.equalsIgnoreCase("bye"));
scan.close();
}
}
Upvotes: 0
Reputation: 34146
The method next()
reads one word. What you should use is nextLine()
which reads a whole line (delimited by a new-line character entered when you press Enter):
text = scan.nextLine();
From JavaDocs:
public String next(): Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
Upvotes: 4