Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    /**
     * 
     * @param version1
     * @param version2
     * @return 0 if equals, 1 if version1 > version2, -1 if version1 < version2
     */
    public static int compareVersion(String version1, String version2) {
        if (version1 == null || version1.length() == 0 || version1.equals("null") || version1.contains("string")
                || version2 == null || version2.length() == 0 || version2.equals("null")
                || version2.contains("string")) {
            // invalid version, can not compare
            return 0;
        }
        if (version1.equals(version2)) {
            // version equals
            return 0;
        } else {
            String[] v1 = version1.split("\\.");
            String[] v2 = version2.split("\\.");
            int l = v1.length;
            if (v2.length < l) {
                l = v2.length;
            }
            if (l > 0) {
                for (int i = 0; i < l; i++) {
                    try {
                        int int1 = Integer.valueOf(v1[i]);
                        int int2 = Integer.valueOf(v2[i]);
                        if (int1 > int2) {
                            return 1;
                        } else if (int1 < int2) {
                            return -1;
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        if (v1[i].compareToIgnoreCase(v2[i]) < 0) {
                            return -1;
                        } else if (v1[i].compareToIgnoreCase(v2[i]) > 0) {
                            return 1;
                        }
                    }
                }
                return 0;
            } else {
                // invalid version, can not compare
                return 0;
            }
        }
    }
}