My code is printing only false. What can be wrong? - java

I am getting output as false, everytime.
My aim is to print true, if String t is present in the same order in String s.
For example:
String s = "gagbgcgd";
String t = "abcd";
Expected output:
true
String s = "gagcgdgb";
String t = "abcd";
Expected output:
false
Here is the code.
public class StringCompare {
public static boolean stringCompare(String t,String s) {
if (t.length() == 0) {
return true;
}
if (s.length() == 0) {
return false;
}
if (t.charAt(0) == s.charAt(0)) {
stringCompare(t.substring(1), s.substring(1));
}
else {
stringCompare(t, s.substring(1));
}
return false;
}
public static void main(String[] args) {
String s = "acaoadaianaga";
String t = "coding";
System.out.println(stringCompare(t,s));
}
}

When you recurse, you don't return the result of the recursion. Change
if(t.charAt(0)==s.charAt(0)){
stringCompare(t.substring(1), s.substring(1));
}
else{
stringCompare(t, s.substring(1));
}
to something like
if(t.charAt(0)==s.charAt(0)){
return stringCompare(t.substring(1), s.substring(1));
}
else{
return stringCompare(t, s.substring(1));
}

The main problem of your code is in the first execution of the recursion always return false no matter what the return value of remaining execution in the recursion.
You should change your code to something like:
if(t.charAt(0)==s.charAt(0)){
return stringCompare(t.substring(1), s.substring(1));
}
else{
return stringCompare(t,s.substring(1));
}
and remove the last return false; statement.

This is because the outer recursive calls you always returns false
except
if(t.length()==0){return true;}
look at Elliott Frisch's answer.

You should use .contains. Example:
boolean istrue = t.contains(s);

Related

Is it possible to make a recusive method in java that doesn't return before your criteria is met?

This is what I've tried:
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
ApplicationGroup dashParamInfo = null;
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
fetchDashboardParamInfo(a.getChildren(), uniqueId);
} else if (a.getUniqueId().equals(uniqueId)) {
dashParamInfo = a;
}
}
return dashParamInfo;
}
I'm simply running throug applicationGroup which is a list of application groups. It's actually a hierarchy of application groups. I'm trying to make the method recurse if the "if"-statement is true, with a.getChildren() as the new a. If the "else if"-statement is true, dashParamInfo should simply be equal to whatever a is at that point, and then the method should return dashParamInfo without further looping. The problem I have is that when the "if"-statement becomes true, it doesn't recurse, it goes inside the statement but then it just goes to return and ends the method right away. What am I doin wrong?
If the correct answer is not found in the current applicationGroup you need to recurse deeper. But if you recurse you need to check if the recurrent call has found what you were looking for; if so, you need to return it.
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
ApplicationGroup dashParamInfo = fetchDashboardParamInfo(a.getChildren(), uniqueId);
if (dashParamInfo != null)
return dashParamInfo;
} else if (a.getUniqueId().equals(uniqueId)) {
return a;
}
}
return null;
}
I think you are missing return before fetchDashboardParamInfo(a.getChildren(), uniqueId);
private static ApplicationGroup fetchDashboardParamInfo(List<ApplicationGroup> applicationGroup, String uniqueId) {
ApplicationGroup dashParamInfo = null;
for (ApplicationGroup a : applicationGroup) {
if (a.getUniqueId() == null || !a.getUniqueId().equals(uniqueId)) {
return fetchDashboardParamInfo(a.getChildren(), uniqueId);
} else if (a.getUniqueId().equals(uniqueId)) {
dashParamInfo = a;
break;
}
}
return dashParamInfo;
}

Java Stacks/Cannot Find Logic Error

For my CS class, I had to create a boolean function isBalanced(String x) that takes a string and evaluates the amount of brackets/parentheses and returns true if the brackets match up to its pair (e.g; { is a pair of }, ( is a pair of ), [ is a pair of ], etc.). The function would return true if the brackets correctly matched up, false if otherwise. For clarification, MyStack() is my own implementation of the Java stack interface if you are wondering what that Object was.
Examples of how the code would work and return:
{A(B[C])D} would return true.
{A(B[C)]D} would return false.
The problem in my code is a logic error. For some reason, my function is returning true if there is a missing bracket, which should return false.
{A(B)C would return false, but my code reads it as true. Do you have any solutions that would help my code work properly? Thanks!
Balancer.java
public static boolean isBalanced(String x) {
MyStack<String> stack = new MyStack();
if (x.substring(0,1).equals("}") || x.substring(0,1).equals(")") || x.substring(0,1).equals("]")) {
return false;
}
for (int i=0; i<x.length(); i++) {
if (x.substring(i,i+1).equals("{") || x.substring(i,i+1).equals("(") || x.substring(i,i+1).equals("[")) {
stack.add(x.substring(i,i+1));
}
if (x.substring(i,i+1).equals("}") || x.substring(i,i+1).equals(")") || x.substring(i,i+1).equals("]")) {
if (x.substring(i,i+1).equals("}") && stack.peek().equals("{")) {
stack.pop();
} else if (x.substring(i,i+1).equals(")") && stack.peek().equals("(")) {
stack.pop();
} else if (x.substring(i,i+1).equals("]") && stack.peek().equals("[")) {
stack.pop();
} else {
return false;
}
}
}
return true;
}
This file, labeled Main.java, is just a tester. I have omitted the other cases where the code works. The reason why the function should return false is that there is a missing } which should be at the end, but there is none, yet my function returns true for some reason.
Main.java
public static void main(String[] args) {
...
String test4 = "{AA[B(CDE{FG()T})V]";
System.out.println("Missing final close (empty stack case)");
System.out.println("Should be false, is: " + Balancer.isBalanced(test4)); // does not work
}
You have a series of conditions that only pop the stack if a matching pair of brackets are found. I think you're overcomplicating things - if an opening bracket is found, push it to the stack. If a closing parenthesis is found, pop the stack and make sure that they match. E.g.:
private static final Map<Character, Character> CLODSE_TO_OPEN = new HashMap<>();
static {
CLODSE_TO_OPEN.put(')', '(');
CLODSE_TO_OPEN.put(']', '[');
CLODSE_TO_OPEN.put('}', '{');
}
public static boolean isBalanced(String x) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < x.length(); ++i) {
char c = x.charAt(i);
if (CLODSE_TO_OPEN.containsValue(c)) {
stack.push(c);
} else if (CLODSE_TO_OPEN.containsKey(c)) {
try {
if (!CLODSE_TO_OPEN.get(c).equals(stack.pop())) {
return false;
}
} catch (EmptyStackException e) {
return false;
}
}
}
return stack.isEmpty();
}

Compare values of return type Boolean and Integer

I have a scenario where an object receiving from UI passes a Boolean value and this is stored in database as an Integer like TRUE=1 and FALSE=0. Now when the flag is changed for ex to FALSE i need to compare its integer value if its 0 then do nothing if 1 then change to 0 and update. The one way is below, but still there maybe a better way to do this.
class AClient {
static Boolean x;
}
class BServer {
static Integer y;
}
public class Demo {
public static void main(String[] args) {
AClient.x = Boolean.TRUE;
BServer.y = 0;
System.out.println(storedValues());
}
private static Boolean storedValues() {
if (AClient.x) {
if (BServer.y.equals(new Integer(1))) {
return true;
} else {
return false;
}
} else {
if (BServer.y.equals(new Integer(1))) {
return false;
} else {
return true;
}
}
}
}
Output: false
Your storedValues method can be reduced to:
return AClient.x.equals(BServer.y.equals(1));
If x and y don't need to ever be null, I would replace them with primitives instead of the wrapper class, then storedValues could look like this:
return BServer.y == 1 == AClient.x;
You could also change the return type of storedValues to boolean.
There's a shorter way to write it:
Instead of:
if (BServer.y.equals(new Integer(1))) {
return true;
} else {
return false;
}
write :
return (BServer.y == 1) ? true : false;

Missing return statement error in Java

I am currently writing a palindrome tester in Java for a class I am taking in high school. I have asked my teacher for assistance and he is also confused as well. I was hoping the community on stackoverflow could help me out. Thank you.
public class Palindrome
{
private String sentence;
public Palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
else
return false;
}
}
You need return isPalindrome();. Otherwise the method isn't returning anything in that case, and it's declared to return a boolean.
Change
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
to
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
In order to have the method complied, JVM need to make sure the method has a return statement for every possible case (which is something you haven't done).
If your code takes this path there is no return statement. If your teacher is confused, you need a new teacher.
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
your last if clause misses a return, if you really want to return false in the else-clause.
You want to use a recursive way to check if the sentence is palindrome. you'd better to return isPalindrome() method inside following snippet
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
This is my code:
public class palindrome
{
private String sentence;
public palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
else
return false;
}
public static void main(String [] args)
{
palindrome p=new palindrome("aabbaa");
if(p.isPalindrome())
System.out.println("yes");
else
System.out.println("no");
}
}

if and else statement

I'm trying to implement a toString method, and the output of the toString depends on the boolean variables. Below is my class and main.
public class Cell {
public int addSpaces;
boolean isEmpty;
boolean isChute;
boolean isLadder;
public Cell() {
addSpaces = 10; //I initialized addSpaces to 10 for testing purpose
}
public boolean isChute() { //first boolean method
if (addSpaces == -10) {
return true;
} else {
return false;
}
}
public boolean isLadder() {//second boolean method
if (addSpaces == 10) {
return true;
} else {
return false;
}
}
public boolean isEmpty() { //third boolean method
if (addSpaces == 0) {
return true;
} else {
return false;
}
}
public String toString() {
String print;
if (isChute = true) //if isChute is true return true.
{
print = "C10"; // toString output = "C10"
} else if (isLadder = true) // if isLadder is true return true
{
print = "L10"; // toString output == "L10"
} else {
print = "---"; // else toString print output = "---"
}
return print;
}
public static void main(String[] arg) {
Cell s = new Cell();
System.out.println(s.addSpaces);
System.out.println(s);
}
}
Regardless of the input state of toString, I basically get the same output "C10".
Can someone tell me what I did wrong?
I'm new to this website so I appreciate any feedback for future reference. Thank you.
You've fallen into one of the languages "gotchas"
This...
if(isChute = true) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else if (isLadder = true) // if isLadder is true return true
print = "L10"; // toString output == "L10"
else
print = "---"
is actually assigning true to isChute. You should be using == not =
Updated
A better approach would be...
if(isChute) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else if (isLadder) // if isLadder is true return true
print = "L10"; // toString output == "L10"
else
print = "---"
If there are only two states that the object can be (either a chute or ladder), you could simply use
if(isChute) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else print = "L10"; // toString output == "L10"
If it can have more then 2 states then I would use an enum type instead.
isChute is assigned to true. So "C10" is being returned all the time by toString().
Change it
if(isChute){
...
}else if(isLadder){
...
}else{
..
}

Categories