Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    private static final String[] AN_EXCEPTIONS = { "one", "180", "110" };
    private static final String AN_AGREEMENT = "\\A(a|e|i|o|u).*";

    /**
     * Check whether this string starts with a number that needs "an" (e.g.
     * "an 18% increase")
     * 
     * @param string
     *            the string
     * @return <code>true</code> if this string starts with 11, 18, or 8,
     *         excluding strings that start with 180 or 110
     */
    public static boolean requiresAn(String string) {
        boolean req = false;

        String lowercaseInput = string.toLowerCase();

        if (lowercaseInput.matches(AN_AGREEMENT) && !isAnException(lowercaseInput)) {
            req = true;

        } else {
            String numPref = getNumericPrefix(lowercaseInput);

            if (numPref != null && numPref.length() > 0 && numPref.matches("^(8|11|18).*$")) {
                Integer num = Integer.parseInt(numPref);
                req = checkNum(num);
            }
        }

        return req;
    }

    private static boolean isAnException(String string) {
        for (String ex : AN_EXCEPTIONS) {
            if (string.matches("^" + ex + ".*")) {
                // if (string.equalsIgnoreCase(ex)) {
                return true;
            }
        }

        return false;
    }

    private static String getNumericPrefix(String string) {
        StringBuffer numeric = new StringBuffer();

        if (string != null) {
            string = string.trim();

            if (string.length() > 0) {

                StringBuffer buffer = new StringBuffer(string);
                char first = buffer.charAt(0);

                if (Character.isDigit(first)) {
                    numeric.append(first);

                    for (int i = 1; i < buffer.length(); i++) {
                        Character next = buffer.charAt(i);

                        if (Character.isDigit(next)) {
                            numeric.append(next);

                            // skip commas within numbers
                        } else if (next.equals(',')) {
                            continue;

                        } else {
                            break;
                        }
                    }
                }
            }
        }

        return numeric.length() == 0 ? null : numeric.toString();
    }

    private static boolean checkNum(int num) {
        boolean needsAn = false;

        // eight, eleven, eighty and eighteen
        if (num == 11 || num == 18 || num == 8 || (num >= 80 && num < 90)) {
            needsAn = true;

        } else if (num > 1000) {
            num = Math.round(num / 1000);
            needsAn = checkNum(num);
        }

        return needsAn;
    }
}