zoukankan      html  css  js  c++  java
  • 循环

    for循环

    格式:

    for(初始化变量;条件;增量){

    循环体}

    初始化变量:定义变量,作用,控制循环次数

    条件:当条件时ture,执行循环,当条件是false,结束循环

    增量:变量自增情况 

    利用for求1到4和

    public class Sum6 {
    public static void main(String[] args) {
    int sum=0;
    for(int i=1;i<=4;i++){
    sum=sum+i;
    }
    System.out.println(sum);
    }
    }

    /*
    循环的嵌套: 循环里面还有循环, for形式多
    for(){

    for(){

    }

    }
    总的循环次数 = 内循环次数 * 外循环的次数
    内循环,是外循环的循环体

    外循环,控制的是行数
    内循环,控制的是每行的个数
    */
    public class ForForDemo{
    public static void main(String[] args){
    for(int i = 0 ; i < 9 ; i++){
    for(int j = 0; j < i+1 ;j++){
    System.out.print("* ");
    }
    System.out.println();
    }
    }
    }

    while循环

    格式:

    while(条件){

    循环体}

    int a=1;

    while(a<10){

    sysou(a)

    a++;

    }

    do   while循环

    格式;
    do{

    循环体}

    while(条件);

    求1-4的数

    public class Sum6 {
    public static void main(String[] args) {
    int a=1;
    do{
    System.out.println(a);
    a++;
    }while(a<5);
    }
    }

    /*
    break 关键字
    作用于循环中,终止循环的作用
    */
    public class BreakDemo{
    public static void main(String[] args){
    int i = 1;
    while(i < 2000){
    if(i == 3){
    break;
    }else{
    System.out.println(i);
    }
    i++;
    }
    }
    }

    /*
    continue 关键字
    作用: 在循环中, 终止本次循环,开始下一次循环
    */
    public class ContinueDemo{
    public static void main(String[] args){
    for(int i = 0 ; i < 10 ; i++){
    if(i%2==0){
    continue;
    }
    System.out.println(i);
    }
    }
    }

    /*
    实现猜数字的小游戏
    随机数一个数字,让用户猜
    结果三种情况:
    中了, 大了, 小了

    随机数: Random
    键盘输入: Scanner
    猜的数字,和随机数进行比较 if 判断
    直到猜中为止, 反复去猜,循环 while
    */
    import java.util.Random;
    import java.util.Scanner;
    public class GuestNumber{
    public static void main(String[] args){
    System.out.println("猜数字开始了");
    System.out.println("输入1-100之间数据");
    //创建Random类变量
    Random ran = new Random();
    //变量.使用功能nextInt()获取1-100随机数
    int ranNumber = ran.nextInt(100)+1;
    //System.out.println(ranNumber);
    //创建Scanner类变量
    Scanner sc = new Scanner(System.in);

    while(true){
    //获取键盘输入
    int number = sc.nextInt();
    //随机数和,用户输入的数据,比较
    if( number > ranNumber){
    System.out.println("猜大了");
    }else if (number < ranNumber){
    System.out.println("猜小了");
    }else{
    System.out.println("中了");
    break;
    }
    }
    }
    }

  • 相关阅读:
    MinGW
    zip ubuntu使用
    7zip ubuntu使用
    ffmpeg入门
    音频采样
    购房需知
    linux网络配置相关
    挂载与卸载
    spring boot启动异常:java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver
    获取配置文件yml的@ConfigurationProperties和@Value的区别
  • 原文地址:https://www.cnblogs.com/cxd1996/p/9987484.html
Copyright © 2011-2022 走看看