Our Even Numbers code in Java.
Even Numbers Class File:
package arithmetic;
public class EvenNumbers {
private int start; // Our starting point
private final int stop; // where we will stop
private String result; // Store result here.
// Our constructor
public EvenNumbers(int first, int last) {
start = first;
stop = last;
result = "Even numbers between " + first + " and " + last + " are: \n";
}
public String prepResult() {
/*
* Loop from start to stop and rip out even numbers;
*/
while (start <= stop) {
if (start % 2 == 0) { // modulo(%) is explained below
result = result + start + "; ";
}
start = start + 1; // increase start by 1
}
return result;
}
}
Main Class File
package arithmetic;
public class Arithmetic {
public static void main(String[] args) {
System.out.println("Welcome to our demonstration sequels");
System.out.println("Hope you enjoy (and follow) the lessons.");
System.out.println("");
/* Use the Even Number class. */
String answer;
EvenNumbers even_data = new EvenNumbers(1, 100); // even numbers between 1 and 100
answer = even_data.prepResult();
System.out.println(answer);
System.out.println();
}
}
Try it out!
Elegance (0.0)