如何在java中返回其他对象可以访问的数组?

时间:2014-09-28 21:56:36

标签: java arrays oop

我想在读取文本文件后返回其他对象可以访问的数组。我的指令解析类是:

import java.io.*;

public class Instruction {
   public String[] instructionList;

   public String[] readFile() throws IOException {
      FileInputStream in = new FileInputStream("directions.txt");
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      int n = 5;
      instructionList = new String[n];

      for (int j = 0; j < instructionList.length; j++) {
          instructionList[j] = br.readLine();
      }
      in.close();   
      return instructionList;
  }

}

以上内容包含一个文本文件,其中包含5行文本。在我的main()中,我想运行该函数,并让其他对象可以访问字符串数组。

import java.util.Arrays;
public class RoverCommand {

  public static void main(String[] args) throws Exception {
      Instruction directions = new Instruction();
      directions.readFile();

      String[] directionsArray;
      directionsArray = directions.returnsInstructionList();

      System.out.println(Arrays.toString(directionsArray));
  }

}

最好的方法是什么?我需要数组的元素是整数,如果它们是数字和字符串,如果它们是字母。附:我是Java的新手。有没有更好的方法来做我正在做的事情?

3 个答案:

答案 0 :(得分:1)

您不必使用泛型。我尝试捕获访问器中的异常,如果有任何事情爆发,则返回null。因此,您可以在继续之前测试返回的值是否为null。

// Client.java
import java.io.IOException;

public class Client {
    public static void main(String args[]) {
        try {
            InstructionList il = new InstructionList();
            il.readFile("C:\\testing\\ints.txt", 5);

            int[] integers = il.getInstructionsAsIntegers();

            if (integers != null) {
                for (int i : integers) {
                    System.out.println(i);
                }
            }
        } catch (IOException e) {
            // handle
        }
    }
}


// InstructionList.java
import java.io.*;

public class InstructionList {
    private String[] instructions;

    public void readFile(String path, int lineLimit) throws IOException {
        FileInputStream in = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        instructions = new String[lineLimit];

        for (int i = 0; i < lineLimit; i++) {
            instructions[i] = br.readLine();
        }

        in.close();
    }

    public String[] getInstructionsAsStrings() {
        return instructions; // will return null if uninitialized
    }

    public int[] getInstructionsAsIntegers() {
        if (this.instructions == null) {
            return null;
        }

        int[] instructions = new int[this.instructions.length];

        try {
            for (int i = 0; i < instructions.length; i++) {
                instructions[i] = new Integer(this.instructions[i]);
            }
        } catch (NumberFormatException e) {
            return null; // data integrity fail, return null
        }

        return instructions;
    }
}

答案 1 :(得分:0)

无法保证在调用returnsInstructionList之前调用readFile。让你returnInstructionList返回null。

我会:

public String[] getContentsFromFile(String fileName) throws IOException {
  FileInputStream in = new FileInputStream(fileName);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  int n = 5;
  instructionList = new String[n];

  for (int j = 0; j < instructionList.length; j++) {
      instructionList[j] = br.readLine();
  }
  in.close();       
  return instructionList;
}

第二部分你可以使用泛型的问题。要达到你想要的效果,你必须采用一种方式来说明它是什么。

例如

public class Foo {
   public ReturnForFoo returnAStringOrIntger(boolean val) {
      if(val){
         return new ReturnForFoo("String", ValueType.STRING) ;
      }
      return new ReturnForFoo(10, ValueType.INTEGER); //int
   } 
}

 public class ReturnForFoo {
     Object value;
     ValueType type;

     public ReturnForFoo(Object value, ValueType type) {
         this.value=value;
         this.type=type
     }
     // Asume you have getters for both value and value type
     public static ENUM ValueType {
          STRING,
          INTEGER,
          UNKNOWN
     }
 }

此代码位于您的主要内容中。

 Foo foo = new Foo();
 String value;
 int val;
 ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
 // NOTE you can use switch instead of if's and else if's. It will be better
 if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
    val = (int) returnForFoo.getValue();
 } else if(returnForFoo.getValueType().equals(ValueType.STRING)){
    value = (String) returnForFoo.getValue(); 
 } else {
    // UNKOWN Case
 }

答案 2 :(得分:0)

检查instructionList是否为空。如果为null,则调用readFile方法。

public String[] returnsInstructionList() {
      if (instructionList== null){
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}

因为readFile可以抛出异常,所以最好使用一个额外的变量。像:

private boolean fileReaded = false;
public String[] returnsInstructionList() {
      if (!fileReaded){
          fileReaded = true;
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}

如果readFile可以同时运行,最简单的方法是使函数同步,比如

private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
    .
    .
    .        
}
public synchronized String[] returnsInstructionList() {
      if (!fileReaded){
          fileReaded = true;
          try { readFile(); } catch(Exception e){}
      }
      return instructionList;
}