【问题标题】:Change from ArrayList to Array of Strings Java从 ArrayList 更改为 Array of Strings Java
【发布时间】:2018-08-23 18:10:04
【问题描述】:

我有这个java 方法,它返回一个ArrayList,但我想返回一个字符串数组。该方法读取文件 words.txt(包含每行一个单词的所有单词),我想将这些单词存储到一个字符串数组中。

这是我已有的代码:

public static ArrayList<String> readFile(){
    File myFile=new File("./src/folder/words.txt");
    Scanner s1=null;

    //Creates ArrayList to store each String aux
    ArrayList<String> myWords = new ArrayList<String>();

    try {
        s1 = new Scanner(myFile);
    }catch (FileNotFoundException e) {

        System.out.println("File not found");
        e.printStackTrace();
    }
    while(s1.hasNext()){
        String aux=s1.next();
        System.out.println(aux);

    }
    s1.close();
    return myWords;
}

我可以更改此代码以返回字符串 [] 吗?

【问题讨论】:

  • “我可以更改此代码以返回字符串 [] 吗?” - 可以,但是。在声明数组之前,您需要知道要到达的数字行。或者,您可以将内容读入ArrayList,然后使用它创建一个新的Strings 数组(因为您将知道需要多少元素)。在旁注中。你根本不应该引用src,一旦程序被编译和导出,它就不会存在。如果出现错误,您也不应该从s1 读取,这将创建一个NullPointerException
  • 看到这个question,也一样
  • 我知道行数,所以我想我可以做到!我应该创建对象字符串数组吗?大小和那些东西?或者你是怎么建议的?请问可以打码吗?这可能会有很大帮助。

标签: java arrays string oop arraylist


【解决方案1】:

您可以致电List.toArray(String[])List&lt;String&gt; 转换为String[]。我也更喜欢try-with-resources 而不是明确关闭ScannerList&lt;String&gt; 接口。类似的,

public static String[] readFile() { // <-- You could pass File myFile here
    File myFile = new File("./src/folder/words.txt");

    // Creates ArrayList to store each String aux
    List<String> myWords = new ArrayList<>();

    try (Scanner s1 = new Scanner(myFile)) {
        while (s1.hasNext()) {
            String aux = s1.next();
            System.out.println(aux);
        }
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    }
    return myWords.toArray(new String[0]);
}

【讨论】:

  • 我正在导入这个:import java.awt.List;但第 5 行“列表”中有错误
  • @Pedro import java.util.List; - 请点击我的回答中的JavaDoc链接
【解决方案2】:

尝试使用集合类的内置函数。

    ArrayList<String> stringList = new ArrayList<String>();
    stringList.add("x");
    stringList.add("y");
    stringList.add("z");
    stringList.add("a");

    /*ArrayList to Array Conversion */
    /*You can use the toArray method of the collections class and pass the  new String array object in the constructor while making a new String array*/
    String stringArray[]=stringList.toArray(new String[stringList.size()]);

    
    for(String k: stringArray)
    {
        System.out.println(k);
    }

【讨论】:

    【解决方案3】:

    最后加上这个:

    String [] arr = myWords.toArray(new String[myWords.size()]);
    return arr;
    

    或者简单地说,

    return myWords.toArray(new String[myWords.size()]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2012-10-27
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      相关资源
      最近更新 更多