迭代数组并打印不同的字符串输出

时间:2019-04-23 14:47:42

标签: java arrays

作为新手,我试图更好地理解循环和数组。我可以使用for循环打印一个字符串数组,并在新行中为每个字符串获取不同的输出,例如,正如我在单个println语句中所演示的那样,例如,“ string1到大写”,“ string2到小写”。

import java.util.Arrays;

public class Examples {

    public static void main(String[] args) {

       String[] strings = new String[] {"LOWERCASE","uppercase","char at index","flow"};

         System.out.println(strings[0].toLowerCase()); //can i do this//
         System.out.println(strings[1].toUpperCase()); //with a       //
         System.out.println(strings[3].charAt(3));     //simple       //
         System.out.println(strings[0].length());      //for loop     //

         for (String name: strings){     

             System.out.println(name);
         }   
    }    
}

使用for循环获得与单个println语句相同的结果。

3 个答案:

答案 0 :(得分:0)

您可以为String上的不同操作定义不同的条件,并在简单的for循环中检查它们(即每个步骤的数字递增)。
请参见此示例,该示例使用取模运算来区分4种不同情况:

public static void main(String[] args) {
    String[] strings = new String[] {"LOWERCASE","uppercase","char at index","flow"};

    for (int i = 0; i < strings.length; i++) {     
        if (i % 3 == 3) {
            System.out.println(strings[i].toLowerCase());
        } else if (i % 3 == 2) {
            System.out.println(strings[i].toUpperCase());
        } else if (i % 3 == 1) {
            System.out.println(strings[i].charAt(3));
        } else if (i % 3 == 0) {
            System.out.println(strings[i].length());
        }
    }
}

运行它,然后找出导致输出的原因。

答案 1 :(得分:0)

您可以做的是扩展for-each循环,以对列表中的每个条目执行每个字符串操作,如下所示:

import java.util.Arrays;

public class Examples {

    public static void main(String[] args) {

        String[] strings = new String[] {"LOWERCASE","uppercase","char at index","flow"};


        for (String name: strings){     
            System.out.println(name.toLowerCase());
            System.out.println(name.toUpperCase());
            System.out.println(name.charAt(3));
            System.out.println(name.length());
        }   
    }    
}

您正在寻找什么吗?

答案 2 :(得分:0)

It's not really clear what is the logic you are trying to accomplish, the order you iterate the names in the println part is kinda random.
What you can do is define array of Functions and then for each name in index i apply the relevant function in the same index:

Function<String,String>[] funcs = new Function[] {
  (Function<String,String>) (s) -> s.toUpperCase(),
  (Function<String,String>) (s) -> s.toLowerCase()
};
for (int i = 0; i < names.length; i++) {
  System.out.println(funcs[i].apply(names[i]));
}