2017-10-11 44 views
-1

我想檢查應用程序版本以實現來自服務器的強制更新功能。我想檢查值,如1.1.5,1.1.6,看看哪個更大,我得到這個值作爲一個字符串從服務器,我得到一個數字格式異常解析該字符串浮動值之前比較。這裏是我的代碼:Android比較具有多個小數點的值

String server_app_version = versionObj.getString("android"); 
String version = info.versionName;  
float server_version = Float.parseFloat(server_app_version); 
float current_version = Float.parseFloat(version); 

如何比較server_version> current_version?

+0

的可能的複製[你如何在Java中比較兩個版本字符串?](https://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in- java) – user3351605

回答

0

嘗試這種形式給出:

var firstInput = "1.1.5"; 
var secondInput = "1.1.6"; 

var firstValues = firstInput.Split('.'); 
var secondValues = secondInput.Split('.'); 

// And then you compare one by une using a for loop 
// if Convert.ToInt32(firstValues[i]) >= Convert.ToInt32(secondsValues[i]) 
// Your logic is there 

我希望它能幫助。

胡安

0

將字符串拆分爲'。'並從左到右投射和比較數字

+0

你可以給我任何這樣的例子 –

1

試試這種方法。

public static int versionCompare(String str1, String str2) { 
    String[] vals1 = str1.split("\\."); 
    String[] vals2 = str2.split("\\."); 
    int i = 0; 
    // set index to first non-equal ordinal or length of shortest version string 
    while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { 
     i++; 
    } 
    // compare first non-equal ordinal number 
    if (i < vals1.length && i < vals2.length) { 
     int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); 
     return Integer.signum(diff); 
    } 
    // the strings are equal or one string is a substring of the other 
    // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" 
    return Integer.signum(vals1.length - vals2.length); 
} 

Alex Gitelman answers

0

試試這個。它可能會幫助你。

Scanner s1 = new Scanner(str1); 
Scanner s2 = new Scanner(str2); 
s1.useDelimiter("\\."); 
s2.useDelimiter("\\."); 

while(s1.hasNextInt() && s2.hasNextInt()) { 
    int v1 = s1.nextInt(); 
    int v2 = s2.nextInt(); 
    if(v1 < v2) { 
     return -1; 
    } else if(v1 > v2) { 
     return 1; 
    } 
} 

if(s1.hasNextInt()) return 1; //str1 has an additional lower-level version number 
return 0;