ive been trying to fix this problem for myself for about 2 hours. I'm guessing someone is going to instantly spot out my problem. So my problem is that a while loop(or .equals is giving an incorrect result). Here's the code:
Integer i = 0;
while(!type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
System.out.println(i + " type=" + type + " - questionType" + questionArray.get(i).questionType);
usedQuestionIndexes.add(i); //if question index has not been used - add it to used indexes
So the problem here is its exiting when the variable "type (string)" when it doesn't equal "questionArray.get(i).questionType (string)" which it shouldn't be. So lets say "type = 'hello'" and "questionArray.get(i).questionType = 'hi'" it is coming out of the loop?
The output from the code from the code above is this:
1 type=general - questionType=sport
So what is the problem here? Why is it saying the first condition is true when its not? the second condition is saying false(which is correct) heres the code for the method "hasQuestionBeenAsked":
public static Boolean hasQuestionBeenUsed(Integer questionIndex) {
for(Integer usedQuestionIndex : usedQuestionIndexes) {
if(questionIndex.equals(usedQuestionIndex)){
return true; //if index is found in usedQuestionIndexes array it will return that the index has been used
}
}
return false;
}
Thanks! If you need any extra info just tell me!
It's very simple - it's because you are negating the false by using the negation operator - (!). So even though you have false, you are ending up with true because (not) false = true. In your case, use
// Remove the negation - !
while(type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
Related
I tried to do this LeetCode daily challenge but I've found out that my code loops infinitely.
I looked through it multiple times, but I cannot find where the problem is. If anyone could spot it, please answer.
public int longestValidParentheses(String s) {
int count, highestOne = 0, index = 0;
boolean isSevered = false;
boolean theEnd = false;
while(!theEnd) {
count = 0;
while(!isSevered) {
if(index<s.length()-2) {
if(s.charAt(index) == '(' & s.charAt(index++) == ')') {count = count + 2;index = index+2;}
else {isSevered = true;}}
else theEnd=true;isSevered=true;
}
highestOne = count;
}
return highestOne;
}
I have 2 suggestions for you:
Use indentation and do not write if/else on the same line as the code associated with them
Always, ALWAYS use bracelets, even if you have only a single command. I think one of the wrongs java did is letting the programmers the free not to use bracelets if there is just a single command after it. It confusing.
So you have 2 mistakes here that make your code run for infinity:
isSevered will always be true after one loop exactly, as you change it to true no matter what happens as it is outside the if else statements, hence the reason I wrote the 2 advices above.
You never changing isSeveres or theEnd at the outside loop. Meaning that if isSevers is true and theEnd is false, you will never enter the internal while and will never exit the outside while.
The two of those combined means that if the condition that make theEnd be initialized with true won't happen at the first run, you will be stuck with infinity loop.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}
OK I have a weird problem. The code is as follows :
The method name is returnMultiPartHeading
if (recursionCount > 6 || i == list.size() - 1)
return -1;
multiPartHeading = multiPartHeading + " " + list.get(i + 1).getText();
Token token = new Token();
token.setText(multiPartHeading);
if (isHeadingType(token)) {
System.out.println("found " + multiPartHeading);
System.out.println("returning ...");
System.out.println("I is " + (i + 1));
return (i + 1);
} else {
returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
System.out.println("returning -1");
return -1;
}
The output is for a sample run is :
found xyz
returning...
I is 2
returning -1
why is this happening?? the if (isHeadingType(token)) evaluates to true , prints the two messages and then it totally skips the return i+1 and goes to return -1 instead. In the place I called it, I get -1 as the returned value instead of getting 2. Why is this happening?? Never saw this behaviour.
It's because in your else block, you don't actually return the result of the recursive call. You just call the method, ignore its result, and then fall through to the section below (with the return -1).
You need to change your else block to
else {
return returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
(assuming that your method really is called returnMultiPartHeading, which somehow doesn't sound right)
Looks like two calls are performed, the first wrote
found xyz
returning...
I is 2
and the second
returning -1
as it is a recursive method I think thats the reason
The if block is the second recursive call, which returns to the first recursive call, which was probably called by the else block. In the else block you do not return the value. Hence it skips out and returns -1.
I have a question about if statements and defining integers.
In this code:
if(matches!=null) {t =1;
for (String match : matches) {
if (t == 1 && "one".equals(match)) {
testSound.start();
t = 2;
System.out.println("the value of t is" + t);
} else if (t == 2 && "two".equals(match)) {
testSound.start();
t = 3;
System.out.println("the value of t is" + t);
}
}
If the first if statement executes and returns 2, and then match = "two", will the else if statement work? If not, how would I make it so that when I set t=2, it is actually t=2. Right now it's not working so let me know!
Everything works correctly: the t++ executes before System.out.println, so by the time the t is printed its value is already 2, not 1. If you need 1 printed, move t++ so that it comes after printing.
The second if statement is not executing after that because match is "one", not "two".
You can do System.out.println("the value of t is" + (t++));.
That way you will first print the value of t to the console than add 1 to its value.
I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.