This is for help with a homework assignment, but the site won't let me tag it as such. FYI: I haven't learned loops besides the while type yet. I need some help with a while loop counting program for Java. I'm new to programming, so I'll try to explain this as best I can. The program will ask the user for a starting number, ending number, and increment. I want it to be able to execute 4 types of scenarios. The first three types work fine, but the last scenario infinitely loops. How can I change my code to meet all 4 types of scenarios? Any explanations or help is appreciated. Below are the scenarios and after them is my code.
starting number < ending number, counts up by increment to ending number and stops: Where do you want to start counting? 35 How far do you want me to count? 60 Increment? 5 COUNTING 35 40 45 50 55 60
starting number > ending number, starting number counts down by increment to ending number and stops: Where do you want to start counting? 44 How far do you want me to count? -22 Increment? 11 COUNTING 44 33 22 11 0 -11 -22
Starting number = ending number, only that number is outputted: Where do you want to start counting? 99 How far do you want me to count? 99 Increment? 3 COUNTING 99
The increment does not evenly count up or down to to the ending number. It's supposed to stop before it reaches the ending number: Where do you want to start counting? 23 How far do you want me to count? 46 Increment? 6 COUNTING 23 29 35 41
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
int counter, limit, inc;
Scanner input = new Scanner(System.in);
System.out.println("Where do you want to start counting?");
counter = input.nextInt();
System.out.println("How far do you want me to count?");
limit = input.nextInt();
System.out.println("Increment?");
inc = input.nextInt();
System.out.println("COUNTING");
System.out.println(counter);
while (counter != limit) {
if (counter < limit) {
counter = counter + inc;
System.out.println(counter);
}
else if (counter > limit) {
counter = counter - inc;
System.out.println(counter);
}
}
}
}