寻找更好的方法来做到以下几点

时间:2015-09-07 20:06:24

标签: java

我需要解析许多字符串,确定它们是int还是double。这是我当前使用的代码。我希望能够简单地使用现有的两个try / catch来保持代码整洁,而不是为所有字符串创建一个。

void camTestButton(ActionEvent event) throws IOException, InterruptedException {

    String cam01 = Cam0GO1.getText();
    String cam02 = Cam0GO2.getText();
    String cam03 = Cam0GO3.getText();
    String cam11 = Cam1GO1.getText();
    String cam12 = Cam1GO2.getText();
    String cam13 = Cam1GO3.getText();

    try {
        int textToInt = Integer.parseInt(cam01);

    } catch (NumberFormatException e) {
        try {
            double textToDouble = Double.parseDouble(cam01);
        } catch (NumberFormatException e2) {

        }
    }
    System.out.println(cam01);
}

我现在有这个工作,但我需要取结果并返回每个textField?

    String cam01 = Cam0GO1.getText();
    String cam02 = Cam0GO2.getText();
    String cam03 = Cam0GO3.getText();
    String cam11 = Cam1GO1.getText();
    String cam12 = Cam1GO2.getText();
    String cam13 = Cam1GO3.getText();
    String[] cams = {cam01, cam02, cam03, cam11, cam12, cam13};

    for (String c : cams) {
        try {
            int textToInt = Integer.parseInt(c);

            } catch (NumberFormatException e) {
                try {
                    double textToDouble = Double.parseDouble(c);
                } catch (NumberFormatException e2) {

                }
            }   
            **System.out.println("Cam0GO01 = " + c.?? etc.);**
        }

2 个答案:

答案 0 :(得分:1)

void camTestButton(ActionEvent event) throws IOException,InterruptedException {
    String [] array = {Cam0GO1.getText(), Cam0GO2.getText(), Cam0GO3.getText()};
    for (String st : array) {
        parseCam(st);
    }
}

public void parseCam(String st) {
      try {
          int textToInt = Integer.parseInt(st);
      } catch (NumberFormatException e) {
          try { 
              double textToDouble = Double.parseDouble(st);
          } catch (NumberFormatException e2) {}
      }
      System.out.println(st);
}

答案 1 :(得分:0)

您需要返回您从方法中确定的类型。您可以使用String或定义自己的enum,也可以只使用内置的Class

private static Class getType(String text) {
    try {
        Integer.parseInt(text);
        return Integer.class;
    } catch (NumberFormatException ex1) {
        try {
            Double.parseDouble(text);
            return Double.class;
        } catch (NumberFormatException ex2) {
            return String.class;
        }
    }
}

Class cam1class = getType(cam1.getText());

如果你想为数组中的所有对象调用一次,那么你可以用结果创建一个地图:

Map<String, Class> camTypes = Arrays.stream(camArray)
    .map(c -> c.getText())
    .collect(Collectors.toMap(Function.identity(), this::getType));

或者,如果您的Cam课程定义为equalshashCode,则可以将其用作键而不是字符串:

Map<Cam, Class> camTypes = Arrays.stream(camArray)
    .collect(Collectors.toMap(Function.identity(), c -> getType(c.getText())));