Java循环语句笔记

一、for循环

1、例:

class Demo1 
{
	public static void main(String[] args) 
	{
		
		for(System.out.println("a");System.out.println("b");System.out.println("c"))
		{
			System.out.println("d");
		}
	}
}

程序编译失败,因为for循环语句的格式为:

 for(初始化表达式;循环条件表达式;循环后操作的表达式)

{
                        执行语句;(循环体)

}

而上面的代码缺少循环条件表达式式,即缺少boolean类型。

2、例:

class Demo1 
{
	public static void main(String[] args) 
	{
		int x = 1;
		for(System.out.println("a");x<3;System.out.println("c"))
		{
			System.out.println("d");
			x++;
		}
	}
}

程序正常运行,结果为a d c d c

3、例:

class ForTest 
{
	public static void main(String[] args) 
	{
		/*
		打印:
		* * * * *
		 * * * *
		  * * *
		   * *
		    *

		*/
		for( int x=1 ; x<=5 ; x++){
			for( int y=1 ; y<x ; y++)
			{
				System.out.print(" ");
			}
			for( int z=x ; z<=5 ; z++){
				System.out.print("* ");
			}
			System.out.println();
		}	
	}
}

运行结果:

二、for和while的特点:

1)for和while完全可以互换

2)格式上的不同,在使用上,有点小区别:如果需要通过变量来对循环进行控制,该变量只作为循环增量存在时,区别就体现出来了,例如下面代码,代码1在循环体外可以正常调用变量x,而代码2不能调用y,因为y是局部变量。

class Demo1 //代码1
{
	public static void main(String[] args) 
	{
		int x = 1;
        while (x<11)
        {
	        System.out.println("x="+x);
	        x++;
        }
        System.out.println("x===="+x);
	}
}
class Demo1 //代码2
{
	public static void main(String[] args) 
	{
		for(int y = 1;y<5;y++)
        {
	        System.out.println("y="+y);
        }
        System.out.println("y===="+y);
	}
}

三、无限循环最简单的形式表现:

while(true){}
for(;;){} //默认循环条件为true

四、使用for循环打印九九乘法表

class ForTest 
{
	public static void main(String[] args) 
	{
		/*
		九九乘法表:
		1*1=1
		1*2=2	2*2=4
		1*3=3	2*3=6	3*3=9
		……
		*/
		for( int x=1 ; x<=9 ; x++){
			for( int y=1 ; y<=x ; y++)
			{
				System.out.print(y+"*"+x+"="+y*x+"\t");
			}
			System.out.println();
		}	
	}
}

运行结果:

五、常用转义字符

\n : 回车

\t : 制表符

\b : 退格

\r :  按下回车键

windows系统中回车符其实是由两个符号组成的 \r\n

linux中回车符是 \n

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值