如何打印数组索引号?

新手上路,请多包涵

如何打印数组的个数?

 import java.util.Scanner;
public class ArrayTest {
    public static void main(String[] args) {
        String[] fruit = new String[5];
        Scanner scan = new Scanner(System.in);

        for(int i=0;i<fruit.length;i++)
        {
            System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
            fruit[i] = scan.nextLine();
        }
        for(String a : fruit) {
            System.out.println(a);
/*How do i add Like the number like this
1.Banana
2.Apple
instead of Banana
           Apple
        }
    }
}

我如何添加像这样的数字 1.Banana 2.Apple 而不是 Banana Apple

原文由 trp 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 349
2 个回答

虽然您的问题不是很清楚,但您似乎只想打印包含内容的数组索引,在这种情况下,您可以按照以下代码操作:

 for(int i=0;i<fruit.length;i++){
    System.out.println((i+1)+"."+fruit[i]);
}

或者,如果您希望数字将索引存储在数组内容中,那么您可以使用:

 for(int i=0;i<fruit.length;i++)
    {
        System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
        fruit[i] = (i+1)+"."+scan.nextLine();
    }

希望能帮助到你。

原文由 Shepherd 发布,翻译遵循 CC BY-SA 3.0 许可协议

此代码将显示具有值的索引号。

  int a[] = {2,9,8,5,7,6,4,3,1};

  for(int i=0;i<a.length;i++)
  {
   System.out.println((i)+"."+a[i]+" ");
  }

输出:0.2 1.9 2.8 3.5 4.7 5.6 6.4 7.3 8.1

原文由 user11913306 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题