Reputation: 93
Hello everyone I am a newbie with the java programming language and have been learning the use of methods, below is a simple method i wrote for adding two numbers but when I run the code, it doe not display any output, please what I am doing wrongly? the code should sum numbers from 2 to 4 in this case
//testing Java methods
public class Methods {
public static void main(String [] args) {
int addition = add (2,4);
System.out.println(addition);
}
//the method for addition
public static int add(int a, int b){
int sum = 0;
for (int i = a; a <= b ; i++)
sum += i;
return sum;
}
}
Upvotes: 0
Views: 132
Reputation: 2104
//testing Java methods
public class Methods {
public static void main(String[] args) {
int addition = add(2,4);
System.out.println(addition);
}
//the method for addition
public int add(int a, int b){ // Place this method in the class.
int sum = 0;
for (int i = a; i <= b ; i++){ // "a <= b" Has to be: i <= b
sum += i;
}
return sum;
}
}
I think this is want you want.
The result will be: 2+3+4 = 9
Upvotes: 0
Reputation: 26067
It was actually running into infinite loop.
try this program (change from a <= b to i <= b
)
public static void main(String[] args) {
int addition = add(2, 4);
System.out.println(addition);
}
// the method for addition
public static int add(int a, int b) {
int sum = 0;
for (int i = a ; i <= b ; i++) {
sum += i;
}
return sum;
}
output
9
Upvotes: 1
Reputation: 1032
for (int i = a; a <= b ; i++)
It should be
for (int i = a; i <= b ; i++)
Upvotes: 4