Java

java如何定义数组并赋值

小亿
86
2024-06-03 19:32:19
栏目: 编程语言

在Java中,可以通过以下方式定义数组并赋值:

  1. 使用数组初始化器(Array Initializer):
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
  1. 使用关键字new创建数组并赋值:
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
  1. 使用循环遍历数组并赋值:
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i + 1;
}

String[] names = new String[3];
String[] characters = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < names.length; i++) {
    names[i] = characters[i];
}

0
看了该问题的人还看了