For loop iterator with methods in java - java

I am try to execute one simple for loop with iteration done by method. Its return value is not assigned
public class DefaultC {
public static void main(String[] args) {
int i = 1;
for(i= 10;i<=50; i=method(i)){
System.out.println(i);
}
}
static int method(int i){
return i++;
}
}

++i increments and then returns i.
i++ returns i and then increments it.

static int method(int i){
return i++;
}
This method is doing post-increment, which means it will return the value of i as it is which is being passed as the method argument, after that it increments the value of i which is now not useful at all since the scope of the variable i is only up to this method.
Try doing pre-increment instead.
return ++i;
EDIT: As per OP's comment
#Prashant by i++ it works, but why i = method(i) cant?
for(i= 10;i<=50; i++){ <-- Here post increment happens
System.out.println(i); <-- At this point value is already being incremented so you can utilize it.
}
Where as
for(i= 10;i<=50; i=method(i)){ <-- Here post increment happens inside method and the value it returns is still `10` not `11`
System.out.println(i); <-- At this point value is same as the previous loop
}

The reason i++ works but increment(i) doesn't is because of the difference in the variable you are incrementing.
i++ is incrementing a local variable, so you see the changes to its value;
increment(i) is copying i to a new variable, which happens also to be named i, and increments that, and after taking its value for the return statement.
The variable local to the loop is left unchanged by the ++, just as int j = i; j++; doesn't change the value of i.
In Java, method parameters​ are always passed by value.
But it is also important to note that even if Java did pass method parameters by reference, there is still a semantic difference between i++ and i = i++ (which is like the i = increment(i) case). The other answer have already covered why i = i++ doesn't work.

i++ returns the value of i and later it do increment.
What you need to do is, to use ++i;
Given Example shows how,
public class DefaultC {
public static void main(String[] args) {
int i = 1;
for(i= 10;i<=50; i=method(i)){
System.out.println(i);
}
}
static int method(int i){
return ++i;
}
}
Here ++i will do increment first and returns later

Related

Why return should be last line of my method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 days ago.
Improve this question
I am trying to solve this problem:
Solve for square root.
And this is my code:
public class Solution {
public int sqrt(int A) {
for(int i=0;i<A;i++)
{
if(A%i==i)
{
return i;
}
}
for(int i=A;i>0;i--)
{
for(int j=0;j<A;j++)
{
if(A%j==j)
{
return j;
}
}
}
}
}
But after I try to run it on Interview Bit it shows an error:
./Solution.java:23: error: missing return statement
}
^
1 error
Now I am not able to even run my code.
Your method should have a return, that's the rules. It's not necessarily in the last line, but there should never be a case when there is no return. With your custom algorithm, your return is always conditional and the compiler will not know in advance whether those conditions will ever be true.
So, the problem is like this:
Lets assume that A is a negative number (e.g. -1):
The 1st loop body will never be executed since i (0) is greater then A (-1)
for(int i=0;i<A;i++)
The 2nd loop body will never be executed since i (-1) is smaller then 0.
for(int i=A;i>0;i--)
therefore - we arrived to the end of the function and there is nothing to return even that the function declared as returning int.
Basically - all paths must have return statement (unless the function is void - and in such a case the return statement can be implicit)
If you have declared a method with expects a return type then you must have to take care of all the scenarios of executing all the blocks in that method. Whatever is the code block the method is executing it must return something of the required type.
Find the missing block in your code below :
public class Solution {
public int sqrt(int A) {
for(int i=0;i<A;i++)
{
if(A%i==i)
{
return i; // returning an int here which is correct
} // what if the the 'if' condition is not met. Add a return type for else
}
for(int i=A;i>0;i--)
{
for(int j=0;j<A;j++)
{
if(A%j==j)
{
return j;
} // same what if the condition is not met add a return in 'else' if required.
}
} // if you are not adding any return in the else block. which is not required in your current program then just add a default return to your function.
}
}
For some more information check this
Although you do have two return statements, the compiler is specifying that it still does not have anything to return if both of your conditions aren't met (false).
So to understand, you would have to ask yourself: What would happen if both of these conditions are false? (Conditions being if (A % i == i) and if (A % j == j))
Solution:
public int sqrt(int A) {
for (int i = 0; i < A; i++) {
if (A % i == i) {
return i;
}
}
for (int i = A; i > 0; i--) {
for (int j = 0; j < A; j++) {
if (A % j == j) {
return j;
}
}
}
return -1; //-1 or 0 is widely returned by default to represent a failed function
}
So basically, when creating a method which is expecting something to be returned, you have to return it outside any conditional statements.
Your method Signature is :
Integer sqrt(int A)
Which says that your method body must return an Integer.
Now, in your code ,you are returning value but when certain condition is true.What if that condition is not true.Compiler is smart enough to find that ,in that case,there is no return value,hence the error.
Return should be the last line of your method not the class. As you have declare that method as 'int type', so you should have returned an int value. Compiler can't identify whether that 'if condition' reaches true in all inputs. so you should place a return 0 at the end of the method.
You're not assuring a return value in every state of your method. Besides that, your code doesn't makes sense.
1.You're dividing by zero in the first if loop (don't do that, it's forbidden)
2.The condition i > 0 in the second for loop will always be false.
At the end it should look something like this
public int sqrt(int A) {
for () {
if () {
return i;
}
}
for () {
for () {
if () {
return j;
}
}
}
return 0;
}
If the only thing you want to do is to square a number, use the Math.pow method, don't reinvent the wheel!
int i = 2;
int square = Math.pow(i, 2);

Program constantly says missing return statement

My program is supposed to be passed 2 array-lists, arrivals and duration, and should return the number of events that can basically take place without overlap. The last thing I did was add the final else if statement to count the last arrival as an event that could take place. However, my code constantly gives a no return statement error although there is a return statement.
class Results {
public static int maxEvents(List<Integer> arrival,List<Integer> duration) {
int counter = 0;
for (int i = 0; i < arrival.size(); i++) {
if (arrival.get(i) + duration.get(i) <= arrival.get(i+1)) {
counter++;
} else if (arrival.get(i)==arrival.get(i+1)) {
counter++;
i++;
} else if (i == arrival.size()-1) {
counter++;
}
return counter;
}
}
}
The return statement which you have written lies within for loop that is incorrect.
please follow below code
class Results {
public static int maxEvents(List<Integer> arrival,List<Integer> duration) {
int counter = 0;
for (int i = 0; i < arrival.size(); i++) {
if (arrival.get(i) + duration.get(i) <= arrival.get(i+1)) {
counter++;
} else if (arrival.get(i)==arrival.get(i+1)) {
counter++;
i++;
} else if (i == arrival.size()-1) {
counter++;
}
}
return counter;
}
}
The Java compiler requires that all methods with a non-void return type either:
Return a value (or throw) on all paths
Definitely don't return a value (e.g. if they contain an infinite loop).
It determines this by looking at the statements in your method to see if they "complete normally". This is a bit of a funny term, but it basically means that execution would move onto the next statement (or the method would finish executing if it is the last statement in the method).
In this case, it looks at the loop:
for (int i = 0; i < arrival.size(); i++) {
// ...
return counter;
}
And it finds that:
The for loop body completes abruptly (it always returns a value)
The for loop might be able to complete normally, because i < arrival.size() isn't a constant (*).
As such, it looks after the for loop to make sure that all following paths return a value (or throw). But this cannot be the case, because there are no statements after the for loop. As such, a compile-time error results.
The easiest way to satisfy the compiler is to put another return after the for loop:
for (int i = 0; i < arrival.size(); i++) {
// ...
return counter;
}
return /* some int */;
Or make the guard expression constant true (or omit it):
for (int i = 0; true; i++) {
// ...
return counter;
}
However, your loop body always returns if entered; so it is basically if (0 < arrival.size()) rather than a loop. And it would only ever return 0 or 1, because counter is incremented at most once.
This is presumably a logical error: the return shouldn't be inside the loop, allowing you to count the number of items in the list which meet the condition:
for (int i = 0; i < arrival.size(); i++) {
// ...
}
return counter;
(*) The compiler doesn't look any deeper than the fact it's not a constant equal to true. For example, i <= Integer.MAX_VALUE isn't constant, and thus is considered to allow normal completion, but it is clearly always true.

My return value returns an error

I have a method called RandomInt, that returns a random number. However, when I try to return the value, it gives me an error, stating that the variable cannot be found. I can't use it as a parameter either, because when I call it in another method, it'll return 0. Any help?
public static int randomInt(int low, int high) {
for (int i = 0; i < 10; i++) {
double x = Math.random();
int e = (int) x * high / low;
}
return e;
}
In Java, the scope of a variable is bound by { } characters (in Javascript this is not the case). That means if a variable is declared in a set of {} (curly brackets), it cannot be referenced outside of these brackets.
This is the case in your code. The variable e is declared in the loop, so you can not use it in the function's return statement. I would suggest declaring e right before the lop.
In java whenever a variable is declared, it have a certain scope. When you declare a variable inside a loop, it is only accessible inside that loop. Because the variable you are returning is declared inside the for loop, this is why it is giving an error. Try declaring a variable outside the loop and then access that in the for loop. You code will look like this :
public static int randomInt(int low, int high)
{
int e = 0;
for (int i = 0; i < 10; i++)
{
double x = Math.random();
e = (int) x * high / low;
}
return e;
}
A method can return only one value (in your case one int), but it can be a composite value (array or object). In this case, you are better off having a loop call your method a bunch of times, and do whatever it needs to do with the result.
Technically, int e's scope is inside the loop body since it is declared inside there. The following code will generate 10 random numbers, and return the last one (as the last one overwrites the 9th, which overwrites the 8th, ...):
public static int randomInt(int low, int high){
int e;
for(int i=0;i<10;i++){
double x=Math.random();
e=(int)x*high/low;
}
return e;
}
You're declaring the variable e inside the loop, then trying to reference it from outside that loop. The below should work:
public static int randomInt(int low, int high)
{
int e;
for (int i=0;i<10;i++)
{
double x=Math.random();
e=(int)x*high/low;
}
return e;
}

Compile error - can somebody please correct me?

I just created a code which represents the sum of integer values from 1 to 10.
public class ArithmeticProgress {
public static void main(String args[]) {
int i = 10;
int n;
System.out.println(arithmeticprogress(n, i));
}
static int arithmeticprogress(int n, int i) {
int result = n;
for (n = 0; n < i; n++)
result += result;
return result;
}
}
Unfortunately, it does not compile and therefore it only shows error. Can somebody tell me how to correct this code? Thank you!
You need to initialize n here.
int n=10; // initialize n to some value
System.out.println(arithmeticprogress(n, i)); //else you will get error here
Use IDE to coding. Then you will get
int n;
System.out.println(arithmeticprogress(n, i));//'n' might not be initialize
Or else you can use n as class level variable. Then it will set to it's default value.
As int n; declare in method main, it won't be initialized as it is a local variable and local variable are not initialized automatically. You need to initialize it explicitly before use. So changing it to int n=0; will work.
You are getting compilation error because in java local variables are stack variables and they must be initialized before they can be used. In your case variable n is used before it is initialized. Initialized it like this and it should work.
int n= 1;
There are two problem in your code.
1. You must need to initialize local variable before to use it. You need to initialize n to 0 or any other value which is applicable for your logic.
2. If you want to get the sum of integer from 1 to 10 than your logic is incorrect that's why you got 1024 as a result ( If you initialize n=1 ). you are adding your current result to previous result which is incorrect. To simply add integer from 1 to 10 i think you didn't need variable n in you code.
For this your method should be as shown below :
static int arithmeticprogress(int i) {
int result = 0;
for (int n = 1; n <=i; n++)
result = result + n;
return result;
}
It will gives you result as 55 which is summation of 1 to 10 integer number.
May this will help you.

how to implement a void method as opposed to a method that returns something?

I am just consfused on how to implement these two methods like how call them or use them? Since the first one is void how does it work?
someone please use and an array and implement this for me or help me understand how the first void method works?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
A function with return type does something (executes code) and returns some result back to the code that called that function. A function without return type executes some code but does not return a result ( because it is not needed in most cases )
Consider this two functions:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
You would call it like this:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
In java everything is passed by value, including references. In your void method, the value of a reference to the array is passed. So while you cannot assign a new int [] to numbers, you are able to change the ints in numbers.
The first method, returning void (i.e., not returning anything) is passed an array as a parameter. What is passed is a reference to an array that is declared and for which memory is allocated outside the method. The method sorts that information in place; when the method returns, the data in that array is then sorted.
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted

Categories

Resources