您的位置:首页 > 编程语言 > Java开发

第三章:Java语言基础II 第1节 For入门

2015-07-12 19:37 381 查看

-1、打印100到200的值 (ForDemo1.java)

public class ForDemo1
{
public static void main(String[] args)
{
// 定义for循环的初始条件和结束条件
int start = 100;
int end = 200;

for(int i = start; i <= end; i++)
{
//打印当前值
System.out.println(i);
}
}
}


-2、打印10到1的值 (ForDemo2.java)

public class ForDemo2
{
public static void main(String[] args)
{
// 定义for循环的初始条件和结束条件
int start = 10;
int end = 1;

for(int i = start; i >= end; i--)
{
//打印当前值
System.out.println(i);
}
}
}


-3、打印10到30之间的所有偶数 (ForDemo3.java)

(1)使用 i+=2 控制

(2)使用 if 判断

public class ForDemo3
{
/*
///1、使用 i+=2 控制
public static void main(String[] args)
{
// 定义for循环的初始条件和结束条件
int start = 10;
int end = 30;

for(int i = start; i <= end; i+=2)
{
//打印当前值
System.out.println(i);
}
}
*/
///2、不使用if条件判断
public static void main(String[] args)
{
// 定义for循环的初始条件和结束条件
int start = 10;
int end = 30;

for(int i = start; i <= end; i++)
{
if( i % 2 == 0 )
{
//打印当前值
System.out.println(i);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: