Java 将单独方法中的ArrayList中的代码关联回主方法?
我理解这很可能只是因为代码的构造很差的问题。然而,在编译时,字典在第11行和第12行中无法识别,因为它只在第二个方法中声明。是否有可能在当前的草案中纠正这一点,或者我最好放弃这条路,尝试另一条路Java 将单独方法中的ArrayList中的代码关联回主方法?,java,Java,我理解这很可能只是因为代码的构造很差的问题。然而,在编译时,字典在第11行和第12行中无法识别,因为它只在第二个方法中声明。是否有可能在当前的草案中纠正这一点,或者我最好放弃这条路,尝试另一条路 import java.util.*; import java.io.*; public class ArrayListReader { public static void main(String args[]) throws Exception { getDi
import java.util.*;
import java.io.*;
public class ArrayListReader {
public static void main(String args[]) throws Exception {
getDictionary();
//Code for Scanners
// Code for inputs
}
public static ArrayList<String> name() throws Exception {
//declare a String ArrayList object "filename"
//Scanner object to read from fileName.txt
// while loop to read from fileName.txt
// Adds the next String to the ArrayList
return file;
}
import java.util.*;
导入java.io.*;
公共类ArrayListReader{
公共静态void main(字符串args[])引发异常{
getDictionary();
//扫描仪代码
//输入代码
}
公共静态ArrayList name()引发异常{
//声明字符串ArrayList对象“filename”
//要从fileName.txt读取的扫描仪对象
//while循环从fileName.txt读取
//将下一个字符串添加到ArrayList
返回文件;
}
}例如,您需要将
getDictionary
的结果分配回某个对象
public static void main(String args[]) throws Exception {
ArrayList<String> dictionary = getDictionary();
publicstaticvoidmain(字符串args[])引发异常{
ArrayList dictionary=getDictionary();
作为旁注,您还应该抛出来自方法的实际
异常,而不仅仅是将它们绑定到最低公分母中。通常,这允许您根据需要以不同的方式处理特定异常字典只是getDictionary中定义的局部变量
方法,因此它在主方法中不可用
您需要从getDictionary方法获取返回值并分配给一个变量,可能类似于:
List<String> dictionary = getDictionary();
List dictionary=getDictionary();
谢谢你的回复,当你这么说的时候非常明显。在这种情况下抛出异常真的有必要吗?我试图避免一次尝试/捕获。@LittleTrain没想到它会抛出一个IOException
是的,向调用方抛出异常是个好主意;)