I'm trying to create a recall program that sends text messages to 200+ people and then searches an email that the replies are forwarded too.
This method is supposed to search the array list of replies that is built using another method, but it doesn't work correctly. It will only work if the very first message on the array list matches the very first number in the contact list.
Those are some other problems, but my main question here is why does it say that the code specifically inside of my for loop is dead code?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
else{
return false;
}
}
return false;
}
This is your code, properly formatted:
public static boolean searchForPhone(String phone) {
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
return false;
}
}
return false;
}
The construct flagged as Dead code is the i++ in the for-loop header. It is indeed dead code because the for loop's body unconditionally makes the method return. Therefore the "step" part of the for header is unreachable aka. dead.
The same fact makes your code perform incorrectly, BTW. Removing the else clause would be a big improvement.
Will this help?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
}
return false;
}
Look you are looping over n-element list. When you get first element on the list you got if/else statement.
So you will HAVE TO either of 2 things, both of witch is return. So your program will exit on first element returned.
To make it simplier, your code is equal to:
CharSequence phoneN = phone;
if (myMessages.size() ==0 ){
return false;
}
return myMessages.get(0).contains(phone);
Try from Window > Preferences > Java > Compiler > Error/Warnings
Change Dead code (e.g 'if(false)') and Unnecessary 'else' statement to Error.
Your loop always returns from the function at the end of the first iteration. This makes i++ dead code since it never executes.
Anyway, remove the else clause to fix the code.
In the else part you need to continue to search. Else if your fist element is not the matching one will return false and not going to check other element.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
//return false this conditional return cause
// the complain it as dead code. Since for loop will become not
//loop
continue; // will search for other elements.
}
}
return false;
}
Now you can simplify this code to following because else part is not really necessary.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
}
}
return false;
}
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 a LinkedBlockingQueue and I want to check if there is a certain order of elements in the queue without removing the elements. I was hoping there was method I could use to peek at a particular spot in the queue. For example, queue.peekSpot(0) would return the head and quque.peekSpot(queue.size()) would return the tail. Right now I have this method but it removes the things it is reading. The queue is a type char by the way.
public boolean checkString(String string) {
if (string.length() < 1) {
return true;
}
char input = queue.take();
if (input == string.charAt(0)) {
return checkString(string.substring(1));
}
return false;
}
If I could use a peekSpot() method, this could be done as follows, greatly simplifying the code.
public boolean checkString(String string){
for(int i = 0; i < string.length(); i++){
if(!(string.charAt(i) == queue.peekSpot(i))){
return false;
}
}
return true;
}
Somebody might say, what if that spot doesn't exist? Well then it might wait for that spot to exist. I am using a queue instead of an ordinary string because this is a serial feed and the string would have to constantly change. Any ideas?
There is no direct way to i.e access items by index. but You can call toArray(), which would return you an array and then you can access index locations. Something like this.
String peekSpot(Queue<String> queue, Integer index){
if(queue == null){
throw new IllegalArgumentException();
}
Object[] array = queue.toArray();
return (String)array[index];
}
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;
}
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.
I'm trying to write a method that looks through an array of objects for a certain color, which is also an object.
public Ghost findFirst(Color c){
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor()==c)
return ghosts[i];
else
return null;
}
}
So if the color of a certain ghost matches color c, then return that ghost. However, I'm getting a dead code warning for i++. Whats wrong with my code? Oh also I'm getting a method error saying this function should return a ghost. I thought I am?
Because you return from the loop on the first iteration! So "i" never gets incremented. Either remove the else block completely or change the "return null" to "continue".
As a separate point, the == is checking referential equality, not object equality. It seems likely you should be using ".equals" instead
fixed code:
public Ghost findFirst(Color c){
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor().equals(c))
return ghosts[i];
}
return null;
}
keep in mind that return terminates the function (including the loop obviously). So if you found the right color ghost - you return it (thus ending your search and never reaching the return null; line). If your for loop found nothing - you get to the last line and return null.
Its because of
else
return null;
!
Because of that return-Statement your Loop will only be executed once.
public Ghost findFirst(Color c){
for (int i=0; i < ghosts.length; i++) {
if (ghosts[i].getColor().equals(c))
return ghosts[i];
}
return null;
}
If I 'unroll' your loop, the code does something like:
public Ghost findFirst(Color c){
if (ghosts[0].getColor()==c)
return ghosts[0];
else
return null;
if (ghosts[1].getColor()==c)
return ghosts[1];
else
return null;
if (ghosts[2].getColor()==c)
return ghosts[2];
else
return null;
//etc...
}
Should be clear from this, that it will never reach the second if, it returns (breaks out of the function) at the first if, true or false.
Your multiple return may be a problem. Sometime it makes it simpler to have one return.
public Ghost findFirst(Color c) {
Color color = null;
for (int i=0;i<ghosts.length;i++) {
if (ghosts[i].getColor().equals(c))
color = ghosts[i];
}
return color;
}