java 中 String 数组怎么动态赋值

如题所述

public class StringTest {
public static void main(String[] args) {
//方法1:知道数组有多长的前提下!
String[] srr=new String[10];
//循环动态赋值!
for (int i = 0; i < srr.length; i++) {
srr[i]="第"+(i+1)+"个字符串";
System.out.println(srr[i]);
}
System.out.println("-------------分割线----------------");
//方法2:用这个比较好,就是不知道数组多长的前提下!
//用容器桥接!
StringBuilder stb=new StringBuilder();//字符串容器!
//随便一个长度,自定义!
for(int i=0;i<10;i++) {
stb.append("第"+(i+1)+"个字符串,");
}
//定义一个数组,然后切割容器即可!
String[] arr=new String(stb).split(",");
//查看切割好的字符串数组!
for(String a:arr)
System.out.println(a);
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-10-30
一维数组的声明方式:
type var[]; 或type[] var;
声明数组时不能指定其长度(数组中元素的个数),
Java中使用关键字new创建数组对象,格式为:
数组名 = new 数组元素的类型 [数组元素的个数]
实例:
TestNew.java:
程序代码:
public class TestNew { public static void main(String args[]) { int[] s ; int i ; s = new int[5] ; for(i = 0 ; i 5 ; i++) { s[i] = i ; } for(i = 4 ; i >= 0 ; i--) { System.out.println("" + s[i]) ; } } }

初始化:
1.动态初始化:数组定义与为数组分配空间和赋值的操作分开进行;
2.静态初始化:在定义数字的同时就为数组元素分配空间并赋值;
3.默认初始化:数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐士初始化。
实例:

TestD.java(动态):
程序代码:
public class TestD { public static void main(String args[]) { int a[] ; a = new int[3] ; a[0] = 0 ; a[1] = 1 ; a[2] = 2 ; Date days[] ; days = new Date[3] ; days[0] = new Date(2008,4,5) ; days[1] = new Date(2008,2,31) ; days[2] = new Date(2008,4,4) ; } } class Date { int year,month,day ; Date(int year ,int month ,int day) { this.year = year ; this.month = month ; this.day = day ; } }

TestS.java(静态):
程序代码:
public class TestS { public static void main(String args[]) { int a[] = {0,1,2} ; Time times [] = {new Time(19,42,42),new Time(1,23,54),new Time(5,3,2)} ; } } class Time { int hour,min,sec ; Time(int hour ,int min ,int sec) { this.hour = hour ; this.min = min ; this.sec = sec ; } }

TestDefault.java(默认):
程序代码:
public class TestDefault { public static void main(String args[]) { int a [] = new int [5] ; System.out.println("" + a[3]) ; } }
相似回答