Numeric sequence generation in Java

Generate the below numeric sequence for n times in java,
12
23
34
…..

Program:


import org.apache.commons.lang3.StringUtils;

import java.util.Scanner;

public class NumericSequence {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Input String:");
        String input = scanner.next();
        System.out.print("Enter Number of times:");
        int n = scanner.nextInt();
        if (StringUtils.isBlank(input) || n == 0) {
            System.out.println("Invalid input");
            System.exit(0);
        } else if (Integer.valueOf(input) == null) {
            System.out.println("Not an integer");
            System.exit(0);
        } else {
            StringBuilder finalSequence = new StringBuilder(input);
            StringBuilder res = new StringBuilder();
            String lastSeq = input;
            for (int i = 1; i <= n; i++) {
                res.setLength(0);
                lastSeq = splitAndAdd(lastSeq);
                finalSequence.append("\n").append(lastSeq);
            }
            System.out.println(finalSequence);
        }

    }

    public static String splitAndAdd(String str) {

        StringBuilder sequence = new StringBuilder();
        String[] stringArray = str.split("");
        for (String digit : stringArray) {
            if (StringUtils.isNotBlank(digit)) {
                sequence.append(Integer.valueOf(digit) + 1);
            }
        }
        return sequence.toString();
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s