我正在开发一个应用程序
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);
}
}
发布于 2015-10-25 22:29:58
除了创建一个新方法之外:
public boolean isNumeric (String s){
try{
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
如果转换是可能的,这将返回true,否则返回false。
发布于 2015-10-25 22:36:49
我同意对混合数据使用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
}
}
}
}
}
发布于 2015-10-25 22:34:46
总体来说,使用String[]
是错误的方法。相反,您应该使用自己的类,这样就不必担心数组中有什么东西了。
https://stackoverflow.com/questions/33335750
复制相似问题