66 909
Assignments Done
99,1%
Successfully Done
In October 2018

Answer to Question #53290 in Java | JSP | JSF for francis

Question #53290
/everytime i run this program it shows my answer is incorrect. Please show me my problem


import java.util.Scanner;

public class Exercise04_22 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter string s1: ");
String string1 = input.next();

System.out.print("Enter string s2: ");
String string2 = input.next();

boolean retVal;
retVal = string1.equals(string2);

if (retVal = true) {
// Returns -1 if not matched.

System.out.println(string2 + " is a substring of " + string1);
} else {
System.out.println(string2 + " is not a substring of " + string1);
}
}
}
Expert's answer
Pay your attention to this code line:
retVal = string1.equals(string2);
Method "equals" return true if and only if those strings are equal.
If you want to check if one string is a substring of another, you can do following:
1) Use method "contains". I'd prefer this way. String implements CharSequence interface, so there shouldn't be any problems.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains%28java.lang.CharSequence%29
2) If you are familiar with regular expressions, there is a method "matches".
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches%28java.lang.String%29

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions