/* * T01n11.java -- This program prints the odd integers from 1 through * the value entered by the user. This program uses a do-while loop * to repeatedly get user input, until that input is acceptable. * * Note that the program handles lists of just one value as special * cases, again to improve the output for the benefit of the program's user. * (The logic of programs is often straight-forward; the little details * -- such as pretty output and error-checking -- are what consume a lot * of programmers' time.) */ import java.util.*; public class T01n11 { public static void main (String [] args) { final int INCREMENT = 2; // an odd# + 2 = the next odd# int counter, // iteration control variable for the while loop limit; // sequence endpoint ended by the user Scanner keyboard = new Scanner (System.in); System.out.print("This program will display all of the odd " + "integers from one through\nany positive " + "integer that you enter.\n\nPlease enter " + "your integer : "); // To force the user to give us a positive integer, we // rely on the following loop. We don't need a priming // read as we do with a while used in this situation, // but we have to add an IF statement to tell the user // what's going on. do { limit = keyboard.nextInt(); if (limit <= 0) System.out.print("I'm sorry; " + limit + " is not a positive " + "integer.\n\nPlease enter an integer value " + "greater than 0 : "); } while (limit <= 0); // If 1 is the only odd integer in the list, we need to // handle it specially for the output to look good. if (limit < 3) { System.out.println("\nThe only odd integer between 1 and " + limit + " is 1."); } else { // Finally: We have a large enough positive integer to // make a loop worth using! Note that the loop // stops one iteration 'short' of the end of the list, // to allow us to use a separate print to terminate the // list neatly. System.out.print("\nThe odd integers from 1 through " + limit + " are :\n\t"); counter = 1; while (counter <= limit - INCREMENT) { System.out.print(counter + ", "); counter = counter + INCREMENT; } System.out.println("and " + counter + "."); } } }