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.
Related
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.
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;
}
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.
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.
I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me.
I'd do it this way:
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
This keeps it as close to your original Java code as possible.
[Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.]
The line
a, b = b, b+a
Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.
t1 = b
t2 = b+a
a = t1
b = t2
You need to store the value of either a or b in a temporary variable first;
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
Java integers can only store the first 46 Fibonacci numbers, use a lookup table.
I'll just translate your earlier code:
public void fibb(int max) {
int a = 0;
int b = 1;
while (a < max) {
System.out.println(a);
int temp = a + b;
a = b;
b = temp;
}
}
Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:
public int Fibb(int index) {
if (index < 2)
return 1;
else
return Fibb(index-1)+Fibb(index-2);
};
Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover.
The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:
Make a list out of 'b' and 'a + b'
Make another list out of references to 'a' and 'b'
Assign all the elements from the second list to the first one
(It might actually be a tuple, I'm not exactly fluent in Python.)
So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.
In general, a statement in Python like
var1, var2, ...varN = expression1, expression2, ...expressionN
is going to translate in Java to
temp1 = expression1;
temp2 = expression2;
...
tempN = expressionN;
var1 = temp1;
var2 = temp2;
...
varN = tempN;
This way all the expressions resolve to values before the assignments happen, and none of the assignments have side effects on the expressions.
If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible.
There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.
public class Fibonacci {
public long fibonacci(int number) {
return fib(0,1,number);
}
private long fib(long result, long next, int n) {
if (n == 0)
return result;
else
return fib(next, result+next, n-1);
}
}
i'll do this
fib = 100;
for(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) {
System.out.print(a + ",");
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
Is certainly wrong. I think switching the first two lines should do the trick