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.
Related
EDIT: Got it working. Still not sure what the weird issue was, but I think it had to do with the fact that I had a loop and recursion.
I don't fully understand the question. but you don't need both, a while loop and recursion. Recursion alone is sufficient here. Use a simple if statement to stop recursion when the number is fully printed.
Note that recursion simplifies putting the digits in the right order here -- with a while loop, you'd need to reverse them somehow...
public static void printInBinary (int num) {
int div = num % 2;
int rem = num / 2;
if (rem > 0) {
printInBinary(rem);
}
System.out.print(div);
}
Your while loop is continuously going because your num-- isn't in the loop, so the number never changes.
public static void printInBinary (int num)
{
int div = (Integer)num%2;
int rem = (Integer)num/2;
while (num >= 1)
{
System.out.print(div);
printInBinary(rem);
num--;//Moved here
}
//removed from here
}
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'm trying to write a for loop that calls the method fibonacci and prints the first 25 numbers in the fibonacci sequence. The problem is I'm a little confused about how to do that correctly. I'm a little confused about when the for loop in the run method calls the fibonacci method do the values inside the fibonacci method reset after reach pass of the for loop? So for example during the first pass of the for loop i = 0 and the values for int a and int b change inside the the fibonacci method. Do the values inside the fibonacci method reset on the next pass of the for loop?
import acm.program.*;
public class Fibonacci extends ConsoleProgram{
private void run(){
for(int i = 0; i <= 25; i++){
fibonacci(i);
println(fibonacci(i));
}
}
private int fibonacci(int n){
int n = 0;
int a = 0;
int b = 1;
while (n < 25);
int c = a + b;
a = b;
b = c;
}
return(a);
}
You're looping in two different places - run() and fibonacci(). Only one of these places should care about the loop, and the other should care about computing Fibonacci(n).
What we can do remove the loop from fibonacci, and only rely on the loop on the outside. Also, we're going to remove that statement int n = 0, since that shadows the parameter you're passing in.
Lastly, we're going to create two new static variables a and b, so that the values of those are preserved with this instance. If you don't do that, then you'd have to rely on either recursion or some other methodology to provide the appropriate values of a and b.
I'm not entirely sure why you need to extend ConsoleProgram, but I'll leave it in for now.
So, here's what it should look like.
public class Fibonacci extends ConsoleProgram {
static int a = 0;
static int b = 1;
public void run() {
for(int i = 0; i <= 25; i++) {
// Print the call to fibonacci(i) with every iteration.
}
}
private int fibonacci(int n) {
int c = a + b;
a = b;
b = c;
return c;
}
}
Fibonacci it's a typical example of an algorithm that can be easily approached with recursion, that's because:
you can divide the entire fibonacci sequence in steps,
in each step you have to do the same thing except for the final step where you got 0,
and the last step is "special" because 0 times any number gives you 0,
so if you apply the same step as before you simply nullify everything, this means that when your counter is 0 you have to do something different from your previous steps and it's:
multiply the result that you have stored by 1 and not by 0 ( or you can leave it as it is, it's the same thing as multiply by 1
exit the loop and terminate the fibonacci sequence
Internet is full of Fibonacci examples, 1 & 2 are more than enough for you.
The variables reset for each iteration of the loop. The variables a, b, and c are local variables that only "live" within the method. Every call to the fibonacci(n) method should start from the beginning of the fibonacci sequence and print out the terms up until the nth term. Therefore, while (n < 25); should not be part of the method. Also, int n = 0 resets n to zero, which is bad because we need to know what n is to get the nth term.
The ideal way to do this loop is:
private void fibonacci(int n) {
int i = 1; // a new variable i to count from the 1st term
int a = 0; // the first term
int b = 1; // the second term
while (i <= n) {
int c = a + b; // the new value for b
a = b; // switch the old a for the new a
b = c; // get the (i + 1)th term for the next iteration
System.out.println(a); // print out the ith term
i++;
}
}
You are not storing the returned int value of fibonacci();
int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
and why do you have another variable n in your fibonacci(int n) ?
Please make sure first your fibonacci method is working. (The infinite while loop, etc.)
public static void main (String args[]){
for(int i = 0; i<25; i++) {
System.out.println(fibonacci(i));
}
}
static int fibonacci(int n){
if(n==0) {
return 0;
}
int a = 0;
int b = 1;
for(int i = 0; i < n; i++){
int temp = b;
b += a;
a = temp;
}
return(b);
}
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.