import java.util.Scanner;
public class TextMsgDecoder {
public static void main(String[] args) {
String message;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter text:");
message = keyboard.nextLine();
System.out.println("You entered: " + message);
if (message.indexOf("IDK") > 0) {
System.out.println("IDK: I don't know");
}
if (message.indexOf("BFF") > 0) {
System.out.println("BFF: best friend forever");
}
if (message.indexOf("JK") > 0) {
System.out.println("JK: just kidding");
}
if (message.indexOf("TMI") > 0) {
System.out.println("TMI: too much information");
}
if (message.indexOf("TTYL") > 0) {
System.out.println("TTYL: talk to you later");
}
}
}
Asked
Active
Viewed 69 times
-2

Dave Newton
- 158,873
- 26
- 254
- 302

Zamina Abdullahi
- 1
- 1
-
3What input are you giving it? And have you tried `>=` instead of `>`? (The former will match at the start of the input line; the latter will match from the second character) – Andy Turner Oct 24 '18 at 23:01
2 Answers
6
if (message.indexOf("IDK") > 0) {
System.out.println("IDK: I don't know");
}
This will only detect IDK
in a string which doesn't start with IDK
, e.g. _IDK
will be detected (since "_IDK".indexOf("IDK") == 1
), but not IDK_
(since "IDK_".indexOf("IDK") == 0
).
If you want to detect IDK
anywhere including the start of the string, use either:
if (message.indexOf("IDK") >= 0) {
or, more idiomatically:
if (message.contains("IDK")) {

Andy Turner
- 137,514
- 11
- 162
- 243
0
youcomparing the input string, where your typing "IDK" to the INDEXVALUE of IDK. its turning your string into an int. so there is no match
try this instead:
if (Objects.equals(message, "IDK")) {
System.out.println("IDK: I don't know");
}
what your doing is getting the index of "IDK" which may be zero, but it wont be greater than 0, so your if never fires

Technivorous
- 1,682
- 2
- 16
- 22
-
1Never compare strings with `==` ([How do I compare Strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java?s=1|589.2131)) – Kevin Anderson Oct 25 '18 at 00:19
-
Syntax Error... not a typo. i caught this question in triage, and missed the java tag. its fixed now. – Technivorous Oct 25 '18 at 00:20