I get an error in the code from this part of my code:
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
}
return true;
}
When I remove the first return true and instead to the last return true, it don't get the error in my eclipse code, but why can't I have the first place and would this be the same? Thanks!
EDIT: The error message from eclipse say: This method must return a result of type boolean. I'm confused because isn't that what I have done?!
Yes, a break must be in the code
Can I write the method in some other way?
EDIT NUMBER 2
Why isn't this code working?
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
}
This method returns a boolean value so I don't understand why I get an error!? The code looks right to me?
Your edit #2 doesn't compile because there is a possibility that your code won't enter the for-loop. This will be the case if customerList.size() is 0. To fix this, you'll simply need to add a return statement after the for-loop as well:
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
return false;
Another point here is that this code doesn't logically make much sense: it will only return true or false based on the first item in your list. And this is probably not what you want. So take a closer look at several of the other answer here, many of which are good examples for how you can do this.
public boolean findCustomer(String inPersonalNumber){
boolean result = false;
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
result = true;
break;
}
}
return result ;
}
When I remove the first return true and instead to the last return
true, it don't get the error in my eclipse code, but why can't I have
the first place and would this be the same?
If you remove the second return statement the code would be able to run and not return a value - this is not possible as you defined the method to have a return type of Boolean. So it must always return a value no matter what.
Just change the second return statement to false, should do what you want.
Looks like you have turned off the Build Automatically feature of eclipse. It maybe complaining about an error that used to be present when you still hadn't typed in your code fully! This can also happen if you have back-dated your system for some reason.
Also, shouldn't you be returning false if the condition doesn't satisfy?
public boolean findCustomer(String inPersonalNumber) {
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)) {
return true;
}
}
return false;
}
First return will return only in case of all conditions satisfied, but this method should be returning boolean as per code. It would be expecting a return in failure case also.
Removing first return won't affect compilation as it has a return in second place which will work without any condtions.
Edit : Answer for your second question
This code has two return's, but what if your customerList is size 0, in that case also, method must return boolean. right? for that only, compiler is asking.
BTW, code doesn't have null checks.
Your final code could be this. Keeping multiple return statements in code in not a good practice.
public boolean findCustomer(String inPersonalNumber) {
boolean retVal = false;
if (!(inPersonalNumber == null || inPersonalNumber.trim().equals("")
|| customerList == null || customerList.size() == 0)) { // inputs are valid to run this check
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (inPersonalNumber.equals(customerList.get(i).getCustomerPersonalNumber()) { // to avoid NPE, kept inPersonalNumber in check
retVal = true;
break;
}
}
}
return retVal;
}
Because your for loop looses meaning if you're returning true anyway.
If you want to stop loop use break; instead of first return.
Related
method code here:
public boolean addItem(MediaItem item)
{
for (int count = 0; count < Library.size(); count++){
String callNum = Library.get(count).getCallNumber();
if(item.getCallNumber().compareToIgnoreCase(callNum) == 0)
{
while( item.getCopyNumber() < Library.get(count).getCopyNumber())
{
int copyNum = item.getCopyNumber();
copyNum++;
item.setCopyNumber(copyNum);
}
Library.add(item);
return true;
} else if (item.getCallNumber().compareToIgnoreCase(callNum) != 0)
{
item.setCopyNumber(1);
Library.add(item);
return true;
}
}
return false;
}
testCases:
public void testAddItem(){
AnytownLibrary newlib = new AnytownLibrary();
assertNotNull(newlib);
MediaItem newItem = new Book();
MediaItem nextItem = new Book();
assertNotNull(nextItem);
assertNotNull(newItem);
newItem.setCallNumber("1");
nextItem.setCallNumber("1");
newlib.addItem(newItem);
assertTrue(newlib.addItem(newItem));
newlib.addItem(nextItem);
assertTrue(newlib.addItem(nextItem));
}
I cannot figure out why this is failing it keep throwing a assertion error here, and its not telling me that its just the output is false so im unsure whats wrong
i have completely tested my get and set methods and they are correct;
and a version of this that just asserts that the (itemname) rather than call numbers return true passed previously, so I'm sure the answer is somewhere in the method itself
Your logic for adding an item to library is wrong. Adding the very first item will always fail, because the for loop with not execute as the size is zero. So nothing will happen. Since this fails all the subsequent addItem calls will also fail.
There are many what to do this, a simple way will be to check if size is zero and add to the list directly and return. Else use ur for loop.
I have this code:
private boolean changeNcheckIP() {
//try 3 times before false
for(int i = 0; i < 3; i++) {
if(changeIP() && checkIP()) { return true; }
}
return false;
}
Intellij give me an warning at changeNcheckIP():
Boolean method changeNcheckIP() is always inverted
How can I fix that?
It is a warning, not an error (you are not obligated to fix it).
IntelliJ is just notifying you that you are always using your method changeNcheckIP() return as inverted.
Meaning that when you are calling the method (so far in your code) you are probably doing something like:
if(!changeNcheckIP()) {
//do something...
}
Notice the ! in if loop, thats what IntelliJ is trying to tell you to "fix".
If you would use:
if(changeNcheckIP()) {
//do something...
}
Warning will disappear (notice the removed "!" ), but you need to INVERT your return value so your IF logic will work properly.
is it possible by any means in the following method that the print statement get executed after the if statement returns true in the for loop?
public boolean contains(Object o) {
if(o == null){
throw new IllegalArgumentException();
}
for(int i = 0; i < size(); i++){
if(o.equals(getNodeAt(i).data)){
System.out.println("contains passed here: "+o+" "+getNodeAt(i)+" "+i);
return true;
}
System.out.println(getNodeAt(1));
}
System.out.println("cointain failed here "+o);
return false;
}
Of course; call the method again. More effectively, efficiently, and specifically with an Object such that o.equals(getNodeAt(i).data is false. The truth is...
"[B]y any means" is a pretty loose constraint; you say...
is it possible by any means in the following method that the print statement get[s] executed after the if statement returns true in the for loop?
I'm saying that YES, that's possible by any means when the means are recalling the method. In fact, it's perpetually true as long as you're using whatever container.
Proof:
Assume that it is impossible by any means in the following method that the second return statement gets executed after the if statement returns true in the for loop.
static String proof(Object o) {
for(int i = 0; i < 1; ++i) {
if (o == null) {
return "I'm returning from the for loop!!!";
}
}
return "I'm now called after the for's return statement (by any means)!! - QED";
}
But given...
public static void main(String...args) {
System.out.println(proof(null));
System.out.println(proof(new String("Hello Proof!")));
}// end main method
the ouput is...
I'm returning from the for loop!!!
I'm now called after the for's return statement!! - QED
Therefore our assumption is wrong and it is possible by some means for the second return statement to get executed after the if statement returns true in the for loop.
;)
A "better" way to phrase that so it's clear what you're asking would be, perhaps, - "Is it possible for the code in a method body to continue to execute after a return statement?"
That answer is no and can be tested in any good IDE as follows.
static String proof(Object o) {
for(;;)
if(true)
return "Donkey Butts";
return "Poops";
}
This basically says forever it is true that I will return "Donkey Butts". In any IDE I'd waste my time using you will get an error for "unreachable statement". The IDE can determine this truth from your code which implicitly is telling you that any time the loop is active and the if is true the code below cannot execute.
No, it is definitely not possible.
No, but it is possible that System.out isn't flushed until after the return statement.
Yes, if you enclose in a try and finally.
public boolean contains(Object o) {
if(o == null){
throw new IllegalArgumentException();
}
for(int i = 0; i < size(); i++){
try {
if(o.equals(getNodeAt(i).data)){
System.out.println("contains passed here: "+o+" "+getNodeAt(i)+" "+i);
return true;
}
} finally {
System.out.println(getNodeAt(1));
}
}
System.out.println("cointain failed here "+o);
return false;
}
Nothing inside a method can be executed after the return statement.
But when you deal with output operations, things can happen quite differently from what you might expect. In fact, writes to an output file/device are often buffered, i.e. written to an internal array. When the array is full, it is sent to the file/device. This happens for efficiency reasons, because writing a few big chunks of data is faster than writing lots of small ones.
This means that these operations sometimes seem to happen long after the place where they appear in the code.
I'm trying to make a boolean method, but it's not recognizing I have a return statement. What should I do?
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
}
Your code does not make sense. There is no point in having a loop if you're always going to run the code inside the loop exactly once. I think you must have misunderstood. What are you trying to do?
Assuming the method only has to return true or false if it is greater than equal to 3,
would recommend to keep it simple.
Also, Please Note:
Loop through the i=0 to i< rankHist.length incase the array contains less than 13 elements you will encounter an ArrayOutOfBoundException.
If it contains more than 13 elements, the output might be incorrect.
.
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<rankHist.length;i++){
if (rankHist[i]>=3){
return true;
}
}
return false;
}
I think what he wants is if every element in the 13 are >=3, he should return a true, else ways he should return a false.
public boolean isThreeKind( int rankHist[])
{
for (int i=0;i<=13;i++)
{
if (rankHist[i]<3)
{
return false; // Will return false if either of the element have value <3
}
}
return true; // Will return true only if all the 13 elements have value >=3
}
This is literally what your code is doing right now:
public boolean isThreeKind( int rankHist[]) {
return rankHist[0] >= 3;
}
That is it, and I am assuming this is not what you are attempting to do. So if you tell us what you are actually trying to accomplish we can help you more.
In java, You always gotta keep track of returning something EVERYWHERE the method can exit. If it can exit without hitting a return statement, you'll see that error.
So, for your code, to modify it and make it see it, you would need to have it say:
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
return false;
}
Or true, if you would rather that.
You should avoid multiple return statement.
You can use a flag. Declare the flag outside the for loop, then assign the value accordingly, and do not miss the break statement.
Do it like that:
public boolean isThreeKind( int rankHist[]) {
boolean value = false;
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
value = true;
break;
}
}
return value;
}
Please find below my implementation for DFS.
protected void DFS(String search) {
for(Tree<T> child : leafs) {
if(child.value.equals(search))
return;
else
child.DFS(search);
System.out.println(child.value);
}
}
The objective is to stop traversal on finding the node whose value is in the variable search. However, the above function goes on traversing the tree even beyond the declared search node. Could someone help me modify the above function?
Thank you.
Edit 1
protected boolean DFS(String anaphorKey) {
boolean found = false;
for(Tree<T> child : leafs) {
if(child.head.equals(anaphorKey))
return true;
found = child.DFS(anaphorKey);
if(found == true)
break;
System.out.println(child.head);
//System.out.println("anaphorKey: "+anaphorKey);
}
return found;
}
Tried implementing the given answer suggestion (#SJuan76). The implementation above isn't working as desired. Could you point me to the place where code is not as per the logic suggested?
rookie, might I suggest an implementation using the classic for-loop (as opposed to the enhanced for-loop being used now) which allows integration of your stop-condition a bit better, something like:
protected boolean DFS(String key) {
boolean found = false;
for(int i = 0; i < leafs.size() && !found; i++) {
Tree<T> child = leafs.get(i);
if(child.head.equals(key))
found = true;
else
found = child.DFS(key);
}
return found;
}
So as soon as your found condition is hit, the 'found' becomes true and your loop stops.
What you may have forgotten is the "found = child.DFS(key)" portion of the recursion, where you need to remember the result of your recursive calls so ALL your for-loops on up the chain all break as soon as you return.
Hope that helps.
Option A (Nice): the function returns a value, when the node is found it returns a different value that if the node was not found. When you call to method, if you get the found value you stop the loop and return the found value too.
Option B (Ugly): When found, thow an Exception (better if it is your own implementation of it). Don't forget to catch it.
Option C (Uglier): The same with global (static) variables.
UPDATE 1:
It looks like your method should run ok now, can you check (System.out.println) if your value is ever found?
In a more personal opinion, I would find
protected boolean DFS(String anaphorKey) {
for(Tree<T> child : leafs) {
if(child.head.equals(anaphorKey))
return true;
if(child.DFS(anaphorKey)) // No need to store value. No need to check == true (it is implicit)
return true; // If we are in this line the value was found, always return true
System.out.println(child.head);
//System.out.println("anaphorKey: "+anaphorKey);
}
return false; // If the method did not exit previously it was because the value was not found, so in this line always return false
}
more readable (but it should work exactly as your implementation)