有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何传入字符串的ArrayList并将每个单独的数组转换为自己的字符串(java)?

因此,我将获取一个包含如下字符串的输入文件:

birthday54
happy75
nifty43
bob1994

这些字符串是ArrayList的一部分。我想通过一个方法传递这个ArrayList,该方法可以获取每个单独的字符串并单独打印出来。那么基本上,我如何获取字符串的ArrayList,分离每个字符串,然后打印这些字符串呢?在我的代码中,while循环条件为true,因此这里有一个无限循环,它只无限输出第一个字符串“birthday54”。我不知道while循环应该具备什么条件。或者我甚至应该有一个while循环。这是我的密码:

    public static void convArrListToString(ArrayList<String> strings){
            int i=0;
            while (true){
                 String[] convert = strings.toArray(new String[i]);  
                 System.out.println(convert[i]);
                }  
            }
    public static void main(String [] args) 
{
    Scanner in = new Scanner(new File("myinputcases.txt"));
    ArrayList<String> list = new ArrayList<String>();
    while (in.hasNext())
        list.add(in.next());

    convArrListToString(list);

共 (3) 个答案

  1. # 1 楼答案

    我相信您只需要迭代ArrayList并使用“Get”方法来获得每个字符串,如下所示:

    for(int i = 0 ; i < list.size(); i++){ 
       System.out.println(list.get(i)); 
    }
    

    也可以使用for each循环

    for(String s : list){ 
     System.out.println(s);
    }
    

    干杯

  2. # 2 楼答案

    看着很痛苦的男人,试试这个,而不是你的while循环:

    for (String s : strings) { 
         System.out.println(s); 
    }
    

    不需要while循环,数组列表是一个Collections对象,它是Java中的一个容器类,可以通过对象和索引进行迭代,因此这应该将每个字符串逐个拉出,直到接近数组列表的末尾

    Resource on collections in java

  3. # 3 楼答案

    改变这一点:

    while (true) {
        String[] convert = strings.toArray(new String[i]);  
        System.out.println(convert[i]);
    }  
    

    为此:

    for (String strTemp : strings) {
        System.out.println(strTemp);
    }
    

    它只输出“生日54”,因为您没有增加i。您可以通过在while语句的末尾添加i++来增加它,但如果在ArrayList中迭代所有值后执行此操作,则会出现错误。看我的答案,你可以简单地使用for循环来迭代ArrayList