Return int as boolean - java

I am a beginner so please bear with me. I decompiled the source code of a professional application. When I copied the source code into eclipse, an error came up with the following code( the error is with the return type):
public boolean method(){
...
...
for(int i = 0; ; i = 1){
return i;
}
How can I change the code to keep it correct but keep the functionality?

You can cast i as a boolean, or change return i; to return i != 0;, which will be true for all non-zero values of i, and false if i == 0.
As a side note, I really see no reason to wrap a return in a for loop. In this case, you might as well just replace both of those lines with return 0; (or return false;, to match the method signature).

Change the return type from boolean to int.
As you can see, your method is returning i which is declared as an int in the for loop, so the return type of your method has to be the same as the type of the variable it returns.

Related

Need help executing a true/false boolean which includes a for-loop and a conditional

Right now I have my boolean setup like this:
public boolean deleteItem(String p) {
for(int i = this.myList.size() - 1; i > -1; i--) {
if(this.myList.get(i) == p) {
this.myList.remove(i);
return true;
} else {
return false;
}
}
}
I'm trying to go through an arraylist and delete string p from the array list.However if string p does exist within the arraylist I need to delete the string and return true. If it does not exist I simply must return false. I'm coding in eclipse right now and it says that the return statements I have right now do not count as the "required" return statement that I need. How can I fix my code so that it has the return statement(s) in the right place?
Why reinvent the wheel?
public boolean deleteItem(String p) {
return this.list.remove(p);
}
You have a pathway through your code that does not return anything. If your list is empty then the loop will not execute and it will fall through to nothing. Also your loop will return as soon as you process your first item with either true or false.
The comment by John is correct.
"Remove the else block and move return false; outside the for loop.
Your function has a number of flaws.
You are doing a reference equality check and not the value equality check. For doing a value equality check, always use the "equals" method. You won't get any compiler errors for this kind of flaws. You will get undesired output.
Not all the control flows in your function has a return statement even though your method signature suggests a non-void return statement. This will produce a compiler error, the one that you are seeing in your code.
You are having multiple return statements. This is neither a compiler error nor a runtime error. However from good programming practice perspective, it's not the best idea to have multiple return statements. You can do a flag based return statement at the very end.
You are removing elements from a collection object while iterating through it. Depending on the type of the collection object you are using, it may throw a ConcurrentModificationException exception at run time. You need to use a fail-safe iterator instead if available.
I have tried to correct your program. See if this makes better sense:
public boolean deleteItem(String p) {
boolean itemFound = false;
//Assuming your myList object returns a fail safe iterator.
//If it returns a fail fast iterator instead, see the next option.
Iterator<String> iter = this.myList.iterator();
while(iter.hasNext()){
if(iter.next().equals(p)) {
iter.remove();
itemFound=true;
}
}
return itemFound;
}
The above program will work if the iterator is fail-safe. E.g. if your myList object is of type CopyOnWriteArrayList, its iterator will be fail safe. But if your myList object is of a type such a plain ArrayList, that returns a fail fast iterator, the above method will give you a CME.
If your myList collection object is of type List, you can try something as easy as:
public boolean deleteItem(String p) {
//removeAll will return true if at least 1 element is removed
return this.myList.removeAll(Collections.singletonList(p));
}
Alternately, if you are using Java 8, you can do something like following:
public boolean deleteItem(String p) {
//removeIf will return true if at least 1 element is removed
return this.myList.removeIf(item -> item != null && item.equals(p));
}
Hope this helps you a bit.

Error: Incompatible types? How else could i do this?

public static int linearSearch(int[] data, int numToFind)
{
int found=-1;
for (int x=0;x<data.length;x++){
**if(data[x] =numToFind)**
found = x ;
break;
}
return found;
}
Where I have my error it says its an incompatible type at if(data[x]=numToFind)
Inside if condition it should be boolean value. You made just a typo, it should be:
if (data[x] == numToFind)
You need to put if(data[x] == numToFind).
With one = it is assignment. With two it is boolean *operator*.
IF statement in java expects boolean. Your code should be
if(data[x] ==numToFind)
This might been a Typo.
A mistake users from C background frequently make is confusing the assignment and equality operators = and ==. If you want to compare two values, you should use a double equal sign since that's how Java works. If you accidentally use a single equal sign, you don't compare values but assign a value to a variable.
Your code would have perfectly worked in C, but it won't work in Java
public static int linearSearch(int data[], int numToFind)
{
int found=-1;
for (int x=0;x<data.length;x++){
if(data[x] == numToFind)
found = x ;
break;
}
return found;
}
Try this.

Program not returning a String

Method:
public String getRowsOf3Stars (int rows)
Description:
Compulsory Exercise 2) Complete the getRowsOf3Stars method which is
passed an int(rows) as a parameter. The method returns a String
containing that number of 3-stars rows.
For example,
getRowsOf3Stars(2) // returns ā€œ***\n***\nā€
If rows is less than 1, returns an empty String.
An example:
getRowsOf3Stars(2) // should return "***\n***\n"
What I wrote:
public String getRowsOf3Stars (int rows) {
String getRowsOf3Stars="***\n";
if (rows<1){
String none="";
return none;
}
else{
for(int starRows=1;starRows<rows;starRows++){
return getRowsOf3Stars;
}
}
}
The error I recieve on CodeWrite:
private String getRowsOf3Stars(int rows) throws Exception {
>> This method must return a result of type String
Can someone please explain why my program isn't returning a String?
change this
for(int starRows=1;starRows<rows;starRows++){
return getRowsOf3Stars(starRows); // your code here don't return any thing here.
Put return ""; as last line of your method to get rid of the error. It's complaining because there is a chance your current lines where you're returning might never be called due to the conditions you have.
If for example you provide an argument rows = 1, the return will never happen.
Java compiler would make sure that there is a string return from the method.
Now see the code,
1) if(rows<1)
then only if will work and return a string.
2)But if (rows>=1)
then it will go to the for loop, and the compiler cannot determine at the compile time that the for loop will execute or not, as this is a runtime mechanism.So its not sure for the compiler that for loop will execute or not.
And if for loop doesn't execute, your method will not return anything.
Now since compiler has to make it sure, that there should be a string return, it is showing that error.
So what you can do is that, in the else clause after for loop you can return a default string as return ""; or as per your requirement.
In addition to the issue of not returning a string, I don't see a reason for the internal loop as you are issuing a return inside the loop. I think this would accomplish what you want:
public String getRowsOf3Stars (int rows) {
String ROWOF3STARS = "***\n";
String returnString = "";
if (rows > 0){
for(int starRows=1;starRows<rows;starRows++){
returnString += ROWOF3STARS;
}
}
return returnString;
}
Hope this helps.

Broken function even though it appears to be correct

I've been testing my app today and somehow a function broke after I've done a completely unrelated change, and most importantly I can't see why it shouldn't work.
Here it is:
public static int componentStrId(String string)
{
for(int i = 0; i < GameMain.ComponentNames.length; i++)
{
Gdx.app.log("GameCoordinator", "componentStrId index: " + i);
if(string == GameMain.ComponentNames[i])
{
return i;
}
}
return -1;
}
Before you ask, yes, the string I feed it is present in the array I search from, and yet the function returns -1. It just cycles pointlessly through the array.
I've got the feeling that Eclipse freaked out, although maybe I'm just blind and can't see an obvious mistake... So what is it, the former or the latter?
Instead of this ...
if(string == GameMain.ComponentNames[i])
Use this ...
if(string.equals(GameMain.ComponentNames[i]))
If you provide
GameMain.ComponentNames[3]
as parameter it would return 3.
If you construct a String separately it would always return -1, as == would return true only if both references point at the same object.

Why is this code giving an "unreachable code" error?

I can't seem to find a way to fix this problem. All i'm doing is declaring an integer and it's telling me that the code is unreachable.
private class myStack{
Object [] myStack = new Object[50];
private void push(Object a){
int count = 50;
while(count>0){
myStack[count]=myStack[count-1];
count--;
}
myStack[0]=a;
}
private Object pop(){
return myStack[0];
int count2 = 0; //Unreachable Code
}
}
Once you return from a method, you return to the method that called the method in the first place. Any statements you place after a return would be meaningless, as that is code that you can't reach without seriously violating the program counter (may not be possible in Java).
Quoting a comment on the question by Jim H.:
You returned from the pop() method. Anything after that is unreachable.
Unreachable code results in compiler error in Java.
In your program the line
int count2 = 0;
will never be reached since it is after the return statement.
Place this line above the return statement to work.
The simple explanation in plain English would be the following:
private Object pop(){
return myStack[0];
int count2 = 0; //Unreachable Code
}
method private Object pop(){} is looking for a return type Object and you just gave that return type by writing return myStack[0]; .So your method does not necessarily reach int count2 = 0; because it assumed that the method already reached its goal.
The last statement in the function should be a return statement.
Linting tools would flag it since it messes with the allocation of new memory after the counter scope ends.
Declare before return myStack[0] that fixes

Categories

Resources