02. PrintingIntegers

Print a list of integers in a rectangular layout, skipping those integers that contain, or area a multiple of, a specified digit. Uses a method (indexOf) to detect if a character is in a given string.

Description: Print a list of integers in a rectangular layout, skipping those integers that contain, or area a multiple of, a specified digit. Uses a method (indexOf) to detect if a character is in a given string.

Create a new Netbeans Porject, name it PrintingIntergers

Netbeans > file > new project > project > java application > <next> > Project Name: PrintingIntegers > <finish>

Type in code:

package asu.printingintegers;

import java.util.Scanner;

public class PrintingIntergers {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a value of n:");
        int n = input.nextInt();
        String nString = "" + n; //length of n treated as string
        int maxDigits = nString.length();
        System.out.println("How many intergers per line?");
        int p = input.nextInt();
        System.out.println("Which digit, and its multoples, to skip?");
        int m = input.nextInt();
        for (int i = 1; i < n; i++){
            if( ((i%m) == 0) || hasM(i,m) ){
                int iLength = ("" + i).length();
                String stars = getStars(iLength);
                System.out.format("%" + (maxDigits + 1) + "s", stars);
            } else {
                System.out.format("%" + (maxDigits + 1) + "d", i);
            }
            if (i % p == 0){
                System.out.println("");
            }
        }
        System.out.println("");
        System.out.println("");
    }

    public static String getStars(int p){
        String stars = "";
        for(int k = 0; k < p; k++){
            stars += "*";
        }
        return stars;
    }

    public static boolean hasM(int i, int m){
        char c = String.format("%s", m).charAt(0);
        String x = "" + i;
        return x.indexOf(c) >= 0;
    }

}

Sample Output:

Please enter a value of n:
100
How many intergers per line?
10
Which digit, and its multoples, to skip?
7
   1   2   3   4   5   6   *   8   9  10
  11  12  13  **  15  16  **  18  19  20
  **  22  23  24  25  26  **  **  29  30
  31  32  33  34  **  36  **  38  39  40
  41  **  43  44  45  46  **  48  **  50
  51  52  53  54  55  **  **  58  59  60
  61  62  **  64  65  66  **  68  69  **
  **  **  **  **  **  **  **  **  **  80
  81  82  83  **  85  86  **  88  89  90
  **  92  93  94  95  96  **  **  99

Last updated