一、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