Skip to main content
2 of 2
Added comments, and removed repetition
holroy
  • 11.5k
  • 1
  • 26
  • 59

Here are some issues in your code as I see it:

  • Repetitive for-loop – You can use one for-loop, if you just switch the step of it
  • No input validation – You don't verify that your input is integer, or loop if it fails
  • No new line at end of output – This is a minor, but you don't end the output with a new line. And it could be argued that you possibly should try to insert newlines somewhere along the way
  • No documentation or comments – It is always nice to have a little documentation, at least if the code isn't dead obivous
  • Missing braces around if- or for-blocks – It is better to always include the braces, to keep you safe of indentation errors and unclear code

If we in addition add a little string.formatting, a static initialization of the scanner, and add a function for validating integer input, we can get the following code:

import java.util.Scanner;

class Main {
    static Scanner scanner;

    /** Make a scanner available for scanInt */
    static {
        scanner = new Scanner(System.in);
    }

    /** Read two integers, and print counting from start through end */
    public static void main(String[] args) {
        
        int start = scanInt("Enter start number: ");
        int end = scanInt("Enter end number: ");
            
        int step = start < end ? 1 : -1;
            
        // Correct end, in order to use inequality test in for-loop
        end += step;
            
        for (int i = start; i != end; i += step) {
            System.out.print(String.format("%d ", i));
        }
        System.out.println();
    }

    /** Generic function guaranteed to return an int */
    static public int scanInt(String prompt) {
  
        System.out.print(prompt);
        while (!scanner.hasNextInt()) {
            System.out.print("Input must be a whole number. Try again: ");
            scanner.next();
        }
        return scanner.nextInt();
    }
}
holroy
  • 11.5k
  • 1
  • 26
  • 59