Reputation: 1
Could you please help me solve this java algorithm?
the idea is to create a method that counts a number from -5 to 30 and then it goes down -1 till reaches -5 then starts again
for example method should return: -5, 0, 5, 10, 15, … , 25, 30, 29, 28, 27, … , -3, -4, -5, 0, 5,..
I have tried the following, but still I cant find a solution.
--
double a = -5;
public double methodx(){
boolean positiveDirection = true;
if(positiveDirection == true) {
if(a != 30) {
a += 5 ;
positiveDirection=false;
return a;
}
else {
a -= 1;
positiveDirection=false;
}
}return a;
Upvotes: 0
Views: 143
Reputation: 21
public void counter(){
int number = -5;
int direction = 1; // -1 negDirection , +1 pos direction
for (int i = 0; i < 100; i++) {
System.out.print(String.valueOf(number) + ',');
if (direction < 0) {
number = number - 1;
if (number == -5)
direction = +1;
} else {
direction = 1;
number = number + 5;
if (number == 30)
direction = -1;
}
}
}
You can convert 100 to any number you want
Upvotes: 0
Reputation: 655
If you just want to print that numbers, you can try this
The loop
variable indicates how many times you want to print that sequence of numbers
public void methodx(){
int loop = 2;
while(loop != 0){
for(int i = -5; i <= 30; i+=5){
System.out.print(i + " ");
}
for(int i = 29; i >= -4; i--){
System.out.print(i + " ");
}
loop--;
}
}
Upvotes: 1