2021-11-12 Java学习

学习视频:https://www.bilibili.com/video/BV18J411W7cE?p=1

switch结构:

case穿透:

判断一个月为哪一个季节:

switch(month){

    case 1 :
    case 2 :
    case 12 :
        System.out.println("冬季");
        break;
    case 3 :
    case 4 :
    case 5 :
        System.out.println("春季");
        break;
    case 6:
    case 7 :
    case 8 :
        System.out.println("夏季");
        break;
    case 9 :
    case 10 :
    case 11 :
        System.out.println("秋季");
        break;
    deafult:
        System.out.println("输入月份有误");

}

水仙花数:

//水仙花数
public class demo{
    public static void main(String[] args){
        int i,j,k;
        int count = 0;
        for(int a = 100 ; a < 1000 ; a++ ){
            i = a % 10;
            j = a / 100;
            k = a / 10 - j*10 ;
            if(a == i*i*i + j*j*j + k*k*k){
                System.out.println(a);
                count ++;
            
            }
        }
        //输出水仙花数的个数
        System.out.println("水仙花数的个数为:"+count);
    }
}

跳转控制语句:

break  终止循环体内容的执行

continue   跳过某一次的循环,继续执行下一次

eg:

for (int i = 1 ; i < 5 ; i++){
    if(i % 2 == 0){
        break;
        //continue;
    }
}

Random:

作用:产生一个随机数

1、导入包

import java.util.Random;

2、创建对象

Random r = new Random();

3、获取随机数

int  number = r.nextInt(10);

import java.util.Random;
public class demo{
    public static void main(String[] args){
        Random r = new Random();
        int number = r.nextInt(10);
        System.out.println(number);
    }
}

注意:

int  number = r.nextInt(10);  //范围为0-9

int  number1 = r.nextInt(10)+1;  //范围为0-10

猜数字游戏:

import java.util.Random;
import java.util.Scanner;
public class demo{
    public static void main(String[] args){
        Random r = new Random();
        Scanner sc = new Scanner(System.in);
        int number = r.nextInt(100);
        while(true){
            int i = sc.nextInt();
            if(number == i){
                System.out.println("猜测正确数字为:" + i);
                break;
            }
            else if(number < i){
                System.out.println("猜大了,请继续猜测");
            }
            else{
                System.out.println("猜小了,请继续猜测");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_54525532/article/details/121294313