Java中的判断语句和基本循环

判断

if语句

例:

判断是否是闰年

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();//接收用户输入的年份

if (n%400==0||(n%100!==0&&n%4==0)){

        System.out.println(n+"是闰年");

}

if-else语句

例:

判断用户输入的月份有多少天

Scanner sc=new Scanner(System.in);

int y=sc.nextInt();//接收用户输入的月份

if (y==1||y==3||y==5||y==7||y==8||y==10||y==12) {

        System.out.println(y+"月有31天");

}else if (y==4||y==6||y==9||y==11) {

         System.out.println(y+"月有30天");

}else{

        if (n%400==0||(n%100!==0&&n%4==0)){

                System.out.println(y+"月有29天");

        }else {

                System.out.println(y+"月有28天");

        }

}

switch语句

判断输入的月份有多少天
Scanner sc=new Scanner(System.in);

int month = sc.nextInt();

switch (month) {
        case 1:

        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
           System.out.println("此月有31天");
            break;
        case 4:
        case 6:
        case 9:
        case 11:
             System.out.println("此月有31天");
            break;


case 2:
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            System.out.println("此月有29"天);
      } else {
        System.out.println("此月有28天");           

        }

break;

循环的条件

        要先有一个变量然后让他趋近于结束,否则就是死循环。有很多东西while循环能写的for循环也能写。

while循环

    while循环常用于对循环次数未知的循环,比如对用户输入数据对错的判断

由于我用java写的while循环不多所以直接拿用户登录的来举例

/**这里不用nextLine是因为nextLine会把回车存放在缓存里影响下一次的数据输入,所以最好不用*
*nextLine

*/

Scanner sc=new Scanner(System.in);

String u = sc.next;

String p = sc.naxt;

String Username="admin",Password="123456";

while(Username==u&&Password==p) {

        System.out.println("登录成功");

}

do-while循环

先运行在判断是否结束

 int x=1;                          //定义变量x,初始值为1
                   do{
                            System.out. println ( “x=”+x);   //打印x的值
                            x++;                       //将x的值自增
                   }while (x<=4);                   //循环条件

for循环

经常用于已知次数的循环(一般用的较多)

就拿乘法口诀表举例:

for (int i=1;i<=9;i++) {

        for (int j=1;j<=i;j++) {

                System.out.printf("%2d",i,j,i*j);

                System.out.println(" ");

        }

        System.out.println();

}

增强型for循环

增强for循环一般是用在遍历数组中

格式是for (ElementType element:arrayName) {}

例:

int a[] = {1,2,3,4,5,6};

for (int i : a) {

        System.out.printf("%2d",i)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值