![](/img/trans.png)
[英]How to find the difference in a Map between two Strings based on their integer values?
[英]How to make difference in String[] between real strings and integer values?
我正在開發一個應用程序
String[][] datos;
我需要為一種方法在所有字符串和整數值之間做出區別。 例如:
datos[0][2]: "hi"
datos[1][1]: "3"
datos[2][2]: "a"
datos[3][0]: "25"
在這種情況下,我只需要3和25個值,但我做不到
Integer.parseInt(datos[1][1]);
每個值。
在我的代碼中,我只列出了特定的情況,但是我想在第一個if語句中列出所有情況。
for(int f=2;f<maxf;f++)
for(int c=3;c<maxc;c++){
if((datos[f][c]!= "A")&&(datos[f][c]!= "-")&&(datos[f][c]!= "")){
nota= Integer.parseInt(datos[f][c]);
if(nota>3)
aprobados.set(f-2, aprobados.get(f-2)+1);
}
}
我同意將String[][]
用於混合數據的反對意見。
但是,如果OP沒有選擇,則以下是測試程序的變體,顯示了如何執行此操作:
public class Test {
public static void main(String[] args) {
int maxf = 4;
int maxc = 3;
String[][] datos = new String[maxf][maxc];
datos[0][2] = "hi";
datos[1][1] = "3";
datos[2][2] = "a";
datos[3][0] = "25";
for (int f = 0; f < maxf; f++)
for (int c = 0; c < maxc; c++) {
if (datos[f][c] != null) {
try {
int nota = Integer.parseInt(datos[f][c]);
System.out.println(nota);
} catch (NumberFormatException e) {
// Deliberately empty
}
}
}
}
}
除了創建一個新方法:
public boolean isNumeric (String s){
try{
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
如果可以強制轉換,則返回true,否則返回false
總體而言,使用String[]
是錯誤的方法。 相反,您應該使用自己的類,這樣就不必擔心數組中現在的位置。
您可以使用正則表達式“ ^ [0-9] * $”檢查字符串是否僅包含數字。 我寧願不使用異常捕獲。 我相信正則表達式匹配會更高效,如下所示:
public static void main(String []args){
int maxf = 4;
int maxc = 3;
String[][] datos = new String[maxf][maxc];
datos[0][2] = "hi";
datos[1][1] = "3";
datos[2][2] = "a";
datos[3][0] = "25";
for(int f = 0; f < maxf; f++){
for(int c = 0; c < maxc; c++){
if(datos[f][c] != null && datos[f][c].matches("^[0-9]*$")){
int nota = Integer.parseInt(datos[f][c]);
System.out.println("datos[f][c] = " + nota);
// if(nota>3)
// aprobados.set(f-2, aprobados.get(f-2)+1);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.