有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在字符串[]中区分实字符串和整数值?

我正在开发一个应用程序,我有

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);
        }
    }

共 (4) 个答案

  1. # 1 楼答案

    总体而言,使用String[]是错误的方法。相反,你应该使用你自己的类,这样你就不必担心你的数组中现在有什么

  2. # 2 楼答案

    创建一个新方法:

    public boolean isNumeric (String s){
        try{
            Double.parseDouble(s);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    

    如果可以进行强制转换,则返回true,否则返回false

  3. # 3 楼答案

    可以使用正则表达式“^[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);
                }
            }
        }
    }
    
  4. # 4 楼答案

    我同意对混合数据使用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
              }
            }
          }
      }
    }