I wrote code to find subsequence string. If the character present in the given another string return true else return false, but it doesn't return anything. What is the problem in my code.
import java.lang.String;
public class Subsequence{
public static void main(String args[]){
String s="";
String t="ajhbuuhyc";
Solution obj=new Solution();
obj.find(s,t);
}
}
class Solution{
public boolean find(String s,String t){
int S=s.length();
int T=t.length();
int i=0,j=0;
if(S==0) return true;
if(S>T || T==0) return false;
while(i<S && j<T){
if(s.charAt(i)==t.charAt(j)) i ;
j ;
}
return i==S;
}
CodePudding user response:
It appears that the problem is with the main method of the Subsequence class. The main method is not calling the find method with any arguments, so the find method is being called with empty string arguments. Because the find method checks if the length of the s string is 0, and if it is, it returns true, the find method will always return true if it is called from the main method as it is currently written.
To fix this issue, you could pass actual string arguments to the find method when it is called in the main method, like this:
public boolean find(String s, String t) {
int S = s.length();
int T = t.length();
int i = 0, j = 0;
if (s.isEmpty() || t.isEmpty()) return false;
while (i < S && j < T) {
if (s.charAt(i) == t.charAt(j)) i ;
j ;
}
return i == S;
}
CodePudding user response:
every method in java has a return;
value. if you write this code
public void foo(){
return;
}
ide tell you that 'return' is unnecessary as the last statement in a 'void' method
return has two options
it stops the method
it return some data
public static int foo() { return 2 2; } public static void main(String[] args) { System.out.println(foo()); // 4 }
}
in your case, you ignore data from method find
write
if (find("", ""))
System.out.println("true"); // true
System.out.println(find("", "")); // true