My return value returns an error - java

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;
}

Related

How do I count Iterations in loop and compare it to the iterations from the other class?

I wrote code that solves polynomials in two ways:
normal form a0x+a1x...an*x
Horner method.
Now, what I need, is to count the amount of multiplications in both classes and compare them. So, my program could decide in which case the Horner method is a better way to solve a polynomial. I couldn't find any ways to count the multiplicators myself.
static int count_2=0;
static int count_1=0;
//---------------------------------------------------------------------------//
public static double evalSimple(double[] a, double x) {
double y_temp = 0;
double y=0;
int n=1;
for(int i=1; i < a.length ; ++i) {
y_temp = (a[i] * Math.pow(x,n));
y = y + y_temp;
++n;
++count_1;
}
System.out.println(count_1);
return y+a[0];
}
//here would be the class to compare the amount of the multiplikations
I tried to initiate the variables count_1 & count_2 and put them in the for-loop, but I didn't get how to return the value (not just to print them in console) of them for the test environment.
A function can always return only one value. But you can make this a result object. I made the example with only one of your methods:
class Result {
double solution;
int iterations;
}
public static Result evalHorner(double[] a, double x) {
Result result = new Result();
for (int i = a.length - 1; i >= 0; i--) {
result.solution = a[i] + result.solution * x;
++result.iterations;
}
return result;
}
Also note that I did not use a global counter variable, so the returned value is fresh for the exact invocation.

For loop iterator with methods in 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

Returning max value in java

Pretty simple question I'm sure, since I'm only just learning.
In a larger class that I am on my way of implementing, we have to provide a method Max to return the maximum value in an array. This is what I have:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
return Max;
}
}
However, the method does not compile. I believe it has something to do with the return type. The program calls up this function (and a similar Min function) like this further on in the program:
System.out.println("[" + window.Min() + " " + window.Max() + "]");
What am I doing wrong?
EDIT: Thanks for all of your answers! Just started learning coding, so trivial mistakes like this one can still cause a whole lot of frustration. Saving my ass, all of you!
Java always considers the possibility of the for loop not being entered, and sees no return statement at the end of the method, giving a missing return statement compiler error. The method is declared to return something, an int, so every possible execution path must return something.
Move return Max; after the end of the for loop, both to satisfy the compiler and to provide a correct "find the max" method.
Incidentally, Java variables usually have a lowercase first letter per normal conventions. The Max variable should be called max. The same applies to the name of the Max method.
I believe this does not compile because there's a way you can get to the end of the method without an explicit return statement.
You need to put that return Max; at the bottom, as opposed to inside the for loop:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
The return statement should not be in the for loop.
It should be
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
It doesn't compile because it is possible to get to the end of the method without anything being returned. If the length of the array is 0 or 1 the loop will not be entered and the return not executed.

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.

Accumulated value -java - simple question

one simple question. I need to sum a value, when a condition is verified, so i have this code
private int sum;
private int sum1;
private int sum2;
private int sum3;
public int pontuationOfplayers() {
if (winner() == 0) {
return sum += 20;
}
else if (winner()==1) {
return sum1 += 20;
}
else if (winner() ==2) {
return sum2 += 20;
}
else
return sum3 += 20;
}
the problem that i have is when the method is called it always start again with 0, so the result must be like, 20, 40, 60, but because of new initialization is always 20.
how can i solve that? like store the value of the variable
thanks!
script:edit
You probably want to make sum a class member, e.g.:
private int sum = 0;
public int pontuationOfplayers() {
if (winner() == 0) {
System.out.println("aqui");
int value0 = 0;
return sum += value0+=20;
}
else {
System.out.println("aquiii");
int value3 = 0;
return sum += value3+=20;
}
}
Based on your update I would suggest doing:
private int sum[] = new int[4];
public int pontuationOfplayers() {
// (assuming winner() returns 3 for the final case)
return sum[winner()] += 20;
}
make sum an instance variable of your class. currently it is a local variable and hence it is initiatilized per method call.
The sum value will need to be created and stored outside this method if it is called several times and you want to maintain the sum. Either store it in a class variable or a local variable in the method that is calling the pontuationOfplayers() method.
Although other answers solve your problem, they don't address what caused it: you are just starting to learn to program.
Read beginner tutorials on Java, Java classes and Java OOP (object-oriented programming). For example, you may start with this question: https://stackoverflow.com/questions/1168919/java-tutorials-for-beginning-programmer
Happy coding!
sum should be a member of the class and thus defined
private int sum = 0;
within the class(but outside the methods). It is then preserved within the instance of the class, exists for the lifetime of that instance and can be modified by the methods within the class.
What you currently have defined exists only for the lifetime of the method invocation, and will go out of scope as soon as you exit that method.

Categories

Resources