我是靠谱客的博主 威武大树,这篇文章主要介绍Java学习(25)增强型for循环,现在分享给大家,希望可以做个参考。

  1. 增强型for循环
    又叫foreach循环
    foreach循环应用:
复制代码
1
2
3
4
int[] arr={1,2,3,4,5}; for(int n:arr) System.out.println(n);

意义是每次都将数组当中的一个元素存放到变量n中。

复制代码
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
26
27
28
29
30
31
32
33
34
35
36
package com.study.array; import java.util.Scanner; public class ArrayDemo1 { public static void main(String[] args) { // 求整型数组的累加和 // 定义整型数组 int[] a=new int[5]; Scanner sc=new Scanner(System.in); // 从键盘接收数据,为数组元素赋值 for(int i=0;i<a.length;i++){ System.out.println("请输入第"+(i+1)+"个元素"); a[i]=sc.nextInt(); } System.out.println("数组元素内容为:"); for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); System.out.println("使用增强型for循环输出数组内容:"); for(int n:a){ System.out.print(n+" "); } // 求数组元素的累加和 int sum=0; for(int i=0;i<a.length;i++){ sum=sum+a[i]; } System.out.println(); System.out.println("数组元素的累加和为:"+sum); } }
  1. 如何对变量a,b的值进行交换
复制代码
1
2
3
4
int a=3,b=5; int temp; temp=a;a=b;b=temp;

最后

以上就是威武大树最近收集整理的关于Java学习(25)增强型for循环的全部内容,更多相关Java学习(25)增强型for循环内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部