【问题标题】:How to print specific element of an array如何打印数组的特定元素
【发布时间】:2019-12-13 04:12:46
【问题描述】:
public static void printBackwards(int[] list) {
if (list.length == 0) {
        System.out.println("");
} else {

    for (int i = list.length - 1; i >= 0; i--) {
            System.out.println("element" + (Arrays.toString(list))+"is " + list[i]);
    }
        System.out.println("");
}

如何打印数组的特定元素。例如,我希望它变为 5,4,3,2,1,0,但它一直打印出整个数组。

【问题讨论】:

  • 你认为Arrays.toString(list) 是做什么的?
  • 这能回答你的问题吗? What's the simplest way to print a Java array?
  • 据我所知你想要i 不是 Arrays.toString(list);或更好System.out.printf("Element %d is %d%n", i, list[i]);

标签: java arrays list integer


【解决方案1】:
System.out.println("element is " + list[i]);

而不是

System.out.println("element" + (Arrays.toString(list))+"is " + list[i]);

【讨论】:

    【解决方案2】:

    数组中的每个元素都通过其索引访问。索引从 0 开始,到 (总数组大小)-1 结束。因此,如果您知道要打印的数组的索引,则可以使用索引号直接访问它,如下所示:

    System.out.println("element is " + list[i] + " at index " + i);
    

    但是看起来您想打印从一个特定索引开始到 0 索引的数组元素。您可以按以下方式执行此操作(假设起始索引为 5,并且您希望以相反的顺序打印 5,4,3,2,1,0):

    int startIndex = 5;
    
    if (list.length < (startIndex + 1)) {
            System.out.println("");
    } else {
    
        for (int i = startIndex; i >= 0; i--) {
                System.out.println("element is " + list[i] + " at index " + i);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要有要显示为单独变量的索引列表。

      check_arr = [5,4,3,2,1,0]
      

      然后在你的循环中你可以检查数组中是否存在索引值(check_arr)然后打印。

      要在没有 if 条件的情况下做同样的事情,你需要有一个起始索引 for 循环。前提是您要显示从一个索引到另一个索引的所有值(从开始到结束)。

      for (int i = start; i >= 0; i--) {
              System.out.println(list[i] + " at index " + i);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-27
        • 1970-01-01
        • 2018-07-24
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        • 1970-01-01
        • 2021-08-04
        相关资源
        最近更新 更多