1
2
3
4
5
6
7
8
9
10
11
12
|
public class OneArry{
public static void main(String[] args) {
double [] num = { 1.9 , 2.9 , 3.4 , 3.5 , 10 ,- 1 };
num[ 0 ]= new Double( 2 ); //通过下标把1.9变为2.0
double sum = 0 ;
for ( int i = 0 ; i < num.length; i++) { //遍历
System.out.println(num[i]);
sum+=num[i]; //求和
}
System.out.println( "一维数组之和为 " + sum);
}
}
|
运行结果:
1
2
3
4
5
6
7
|
2.0
2.9
3.4
3.5
10.0
- 1.0
一维数组之和为 20.8
|
二维数组遍历与求和:(方式一)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class TwoArry{
public static void main(String[] args) {
int sum= 0 ;
int num [][] ={
{ 1 , 2 , 3 , 4 , 5 },
{ 6 , 7 , 8 , 9 , 10 },
{ 11 , 12 , 13 , 14 , 15 },
{ 16 , 17 , 18 , 19 , 20 },
{ 21 , 22 , 23 , 24 , 25 }} ;
System.out.println( "输出二维数组:" );
num[ 0 ][ 0 ]= new Integer( 100 ); //通过下标把数组里的1变为100
for ( int i= 0 ;i<num.length;i++){ //遍历,排列
for ( int j= 0 ;j<num[i].length;j++){
System.out.print(num[i][j]+ "\t" );
sum+=num[i][j]; //求和
}
System.out.println();
}
System.out.println( "二维数组之和为:" +sum);
}
}
|
运行结果:
1
2
3
4
5
6
7
|
输出二维数组:
100 2 3 4 5 6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
二维数组之和为: 424
|
二维数组遍历与求和:(方式二)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class TwoArry{
public static void main(String args[ ]){
int [][]num= new int [ 5 ][ 5 ];
int count= 1 ; //数组从1开始循环
int sum= 0 ;
for ( int i= 0 ;i<num.length;i++){
for ( int j= 0 ;j<num[i].length;j++){
num[i][j]=count++; //count添加到数组里
sum+=num[i][j]; //求和
// System.out.println(num[i][j]); //打印出所有数组
}
}
System.out.println( "二维数组之和为:" +sum);
System.out.println( "输出二维数组:" );
for ( int i= 0 ;i<num.length;i++){ //进行排列
for ( int j= 0 ;j<num[i].length;j++){
System.out.print(num[i][j]+ "\t" );
}
System.out.println();
}
}
}
|
运行结果:
1
2
3
4
5
6
7
|
二维数组之和为: 325
输出二维数组:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
|
注解:num.length表示行数,num.length[i]表示列数
原文链接:https://www.idaobin.com/archives/328.html