while和for循环的基本语法
当实际情况中某种操作具有规律性和重复性,这时在程序中需要引入循环语句。被重复执行的语句称之为循环体,决定循环是否继续的成为循环的终止条件。
循环语句的常用用法:
循环语句:可以让一部分代码,反复执行
1.while循环
编写格式:
while(条件){
循环体;
}
当条件是true,就执行循环体,执行完循环体后,
程序再次执行while中的条件,如果条件还是true,
任然执行循环体,while中的条件是false,循环就
结束了
2.do…while循环
编写格式:
do{
}while(条件);
执行循环体,执行完循环体后,程序再次执行while中
的条件,如果条件还是true,任然执行循环体,while
中的条件是false,循环就结束了.
3.for循环:
编写格式:
for(初始化变量;条件;增量){
循环体;
}
初始化变量:定义变量,作用,控制循环的次数
条件:当条件是true,执行循环体,如果条件false,结束循环
增量:变量自增情况
4.循环的嵌套:循环里面还有循环,for形式多
for(){
for(){
循环体;
}
外循环,控制行数
内循环,控制每行的个数
while和for循环代码实现:
import java.util.Scanner;
public class WhileDemoAndIfDemo{
public static void main(String[] args){
System.out.println();
System.out.println("---------------while--------------");
//while循环使用
WhileDemo1();
System.out.println();
System.out.println("---------------do..while----------");
//do..while循环的使用
DoWhile();
System.out.println();
System.out.println("---------------for----------------");
//for循环的使用
ForDemo1();
System.out.println("实现while死循环请按1"+" " +"实现for死循环请按0");
//输入流
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
if(i == 1){
System.out.println("实现了while死循环");
WhileDemo2();
}else if(i == 0){
System.out.println("实现了for死循环");
ForDemo2();
}else{
System.out.println("输入数字有误");
}
System.out.println();
System.out.println("---------for嵌套循环--------------");
ForDemo3();
//
System.out.println();
System.out.println("---------break和continue--------------");
BreakAndContinue();
}
//While循环使用
public static void WhileDemo1(){
//输出1-4之间的整数
//定义变量,整数类型,循环条件
int i = 1;
while(i < 11){
System.out.print(i+"\t");
if(i % 5 == 0){
System.out.println();
}
i++;
}
}
//do... while循环使用
public static void DoWhile(){
int i = 1;
do{
System.out.print(i+"\t");
if(i % 5 == 0){
System.out.println();
}
i++;
}while(i<11);
}
//for循环的使用
public static void ForDemo1(){
int c = 0;
//for循环,输出0-10
for(int i = 1; i < 11; i++){
System.out.print(i+"\t");
c++;
if(c % 5 == 0){
System.out.println();
}
}
}
//While形式死循环
public static void WhileDemo2(){
while(true){
}
}
//for形式死循环
public static void ForDemo2(){
for( ; ;){
}
}
//嵌套循环
public static void ForDemo3(){
byte c = 0;
for(int i= 0; i < 10; i ++){
for(int j = 0;j < 10; j++){
System.out.print("*\t");
c++;
if(c%10 == 0){
System.out.println(" ");
}
}
}
}
//break和continue
public static void BreakAndContinue(){
int c = 0;
for(int i= 0; i < 6; i++){
for(int j = 0 ;j < 6 ;j++){
c++;
if(j == 2 ){
System.out.print("\t");
continue;
}
System.out.print("*\t");
if(c%6 == 0){
System.out.println();
}
}
}
}
}