Java语言基础------循环流程控制
循环流程控制
while循环
- while循环原理案例:
案例代码:
public static void main(String[] args) {
/** * while 循环演示 * 将一个数字按照10进制拆分 */
Scanner console = new Scanner(System.in);
System.out.print("输入一个数字:");
int num = console.nextInt();
while(num>0) {
int last = num%10;
num /= 10;
System.out.println(last);
}
}
do while循环
- do while循环原理案例:
案例代码:
public static void main(String[] args) {
/** * do while 循环演示 * 检查输入分数是否是百分制数据 */
Scanner console = new Scanner(System.in);
int score;
do {
System.out.print("输入分数:");
score = console.nextInt();
}while(!(score>=0 && score <=100));
System.out.println("成功:"+score);
}
for 循环
- for 循环原理案例:
案例代码:
public static void main(String[] args) {
/* * for 循环流程控制 * 控制输出50个Hello World! */
for(int i=0; i<50; i++) {
System.out.println("Hello World!");
}
}
for循环特殊用法
省略for的第一个表达式:
public static void main(String[] args) {
/* * for 循环的特殊用法 * 1. 默认时候循环变量i的作用域:for循环内部 * 2. 可以将循环变量在循环外部定义,扩大循环 * 变量作用域 * 3. for循环可以省略 初始化 表达式。 */
int i=0;
for(; i<100; i++) {
System.out.println(i);
}
System.out.println(i);
}
省略递增表达式
public static void main(String[] args) {
/* * for 循环特殊用法,省略递增表达式 * 1. 省略递增表达式,在for循环内部控制递增变量 */
for(int i=0;i<51;) {
System.out.println(i++%3); //0 1 2 0 1 2
}
}
for省略3个表达式
public static void main(String[] args) {
/* * for 循环省略3个表达式 * * 1. for循环省略3个表达方是死循环 * 2. 经常要与 break 配合结束循环 */
Scanner console = new Scanner(System.in);
int score;
for(;;){ //死循环
System.out.print("输入0~100:");
score = console.nextInt(); //88
if(score>=0 && score<=100) {
break;
}
System.out.println("错误!再来");
}
System.out.println(score);
}
在for循环中定义多个变量
public static void main(String[] args) {
/* * 在for循环中定义多个变量 * 好处是可以将变量的作用域控制在for循环 * 内部,在后续的for循环中可以重新定义变量i j */
for(int i=1, j=6;i<=6; i+=2, j-=2) {
System.out.println("i,j="+i+","+j);
}
//后续的for循环中可以重新定义变量i j
for(int i=1, j=100;i<=6; i+=2, j-=2) {
System.out.println("i,j="+i+","+j);
}
}
还没有评论,来说两句吧...