1.for与语句
/*
for语句
for(初试表达式;条件表达式;循环后的操作表达式) {
循环体;
}
*/
class Demo1_for {
public static void main(String[] args) {
int i,x,y,z;
for(i=100 ; i <= 999;i++) {
x = i / 100;
y = (i % 100) / 10;
z = (i % 100) % 10;
if(i == x * x * x + y * y * y + z * z * z ) {
System.out.println(i + "是水仙花数");
}
}
}
}
2.while语句
/*
while语句:
初始化语句;
while(判断条件语句) {
循环体语句;
控制条件语句;
}
*/
class Demo1_While {
public static void main(String[] args) {
int i = 100,x,y,z,count = 0;
while(i < 1000) {
x = i / 100;
y = (i % 100) / 10;
z = i % 10;
if(i == x * x * x + y * y * y + z * z * z) {
count++;
}
i++;
}
System.out.println("count = " + count);
}
}
3.do … while语句
/*
do while循环:
初始化语句;
do {
循环体语句;
控制条件语句;
}while(判断条件语句);
*/
class Demo1_DoWhile {
public static void main(String[] args) {
int i = 1;
do{
System.out.println("i = " + i);
i++;
}
while (i <= 10);
}
}
4./*
while和dowhile的区别
*/
class Demo1_DoWhile {
public static void main(String[] args) {
int i = 11;
do{
System.out.println("i = " + i);
i++;
}
while (i <= 10);
System.out.println("..........................");
while (i <= 10){
System.out.println("i = " + i);
i++;
}
}
}
5.for和while循环的小区别.
for语句执行完之后变量会被释放,不能继续使用.
while语句在执行完之后,初始化的变量还可以继续使用.
如果在循环结束之后仍然要继续使用控制循环的变量则用while语句,不再继续使用则使用for循环,因为变量在内存中消失,可以提高内存的使用的效率
主要看变量定义的作用域在那里.
6.System.out.println和System.out.print的区别,println在每次输出之后都会自动打的加上一个换行.而print没有.
class Demo1_Print {
public static void main(String[] args) {
int i,j;
for(i = 1;i <= 4;i++) {
for(j = 1;j <= 5;j++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
class Demo1_Println {
public static void main(String[] args) {
int i,j;
for(i = 1;i <= 4;i++) {
for(j = 1;j <= 5;j++) {
System.out.println("*");
}
}
}
}
7./*
控制跳转语句
A.break
只能在switch和循环中使用
B.continue
只能在循环中使用
*/
class Demo1_Break {
public static void main(String[] args) {
for(int i = 1;i <= 10;i++) {
if(i == 8)
break; //跳出循环
System.out.println("i = " + i);
}
}
}
class Demo1_Continue {
public static void main(String[] args) {
for(int i = 1;i <= 10;i++) {
if(i == 8)
continue;//终止本次循环,进行下次的循环
System.out.println("i = " + i);
}
}
}
/*return的作用
返回
它的作用不是结束循环的,而是结束方法的
return是结束方法
break是跳出循环
continue是终止本次循环继续下次循环
*/