gpt4 book ai didi

java - 如何在java中返回一个可由其他对象访问的数组?

转载 作者:行者123 更新时间:2023-12-01 12:29:09 27 4
gpt4 key购买 nike

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

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 新手。有更好的方法来做我正在做的事情吗?

最佳答案

您不必使用泛型。我 try catch 访问器中的异常,并在出现任何问题时返回 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;
}
}

关于java - 如何在java中返回一个可由其他对象访问的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26090063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com