用java写:已知数组 a1= {"吕布","刘备","赵云","李白","小乔",},需要新建数组b1,并增加三个英雄分别是:老夫子,黄忠,孙策
时间: 2024-03-30 11:31:35 浏览: 112
要用Java写一个程序来实现这个需求,可以按照以下步骤进行操作:
1. 首先,创建一个名为a1的字符串数组,并初始化它的元素为已知的英雄姓名:
```java
String[] a1 = {"吕布", "刘备", "赵云", "李白", "小乔"};
```
2. 接下来,创建一个新的字符串数组b1,并将a1数组中的元素复制到b1数组中:
```java
String[] b1 = new String[a1.length + 3];
System.arraycopy(a1, 0, b1, 0, a1.length);
```
3. 然后,将新的英雄姓名依次添加到b1数组的末尾:
```java
b1[a1.length] = "老夫子";
b1[a1.length + 1] = "黄忠";
b1[a1.length + 2] = "孙策";
```
完整的Java代码如下所示:
```java
public class Main {
public static void main(String[] args) {
String[] a1 = {"吕布", "刘备", "赵云", "李白", "小乔"};
String[] b1 = new String[a1.length + 3];
System.arraycopy(a1, 0, b1, 0, a1.length);
b1[a1.length] = "老夫子";
b1[a1.length + 1] = "黄忠";
b1[a1.length + 2] = "孙策";
// 输出b1数组的元素
for (String hero : b1) {
System.out.println(hero);
}
}
}
```
运行以上代码,你将会得到一个新的数组b1,其中包含了原始数组a1的元素以及新增的三个英雄姓名。
阅读全文