Java基础语法

1、基础语法

Hello Wolrd

  • 首先定义类

    —— public class 类名

  • 在类定义之后加上一对大括号

    —— {}

  • 在大括号中间添加一个主(main)方法/函数

    —— public static void main(String[] args){}

  • 在主方法的大括号中间添加一行输出语句

    —— System.out.println(“Hello World”)

  • 完整代码

  • public class HelloWorld{
    public class static void main(String[] args){
        System.out.println("Hello World!")
        }
    }
    
  • Javac —— 编译 javac HelloWorld.java

  • Java + HelloWorld 运行

初学者注意事项

  • 单词拼写问题

    — class > Class

    — String > string

    — System > system

    — main > mian

  • 中文符合问题

    — 提示非法字符

1.1、Java入门

1.1.0、注释

注释

// #单行注释

/*…*/ #多行注释

/...*/ #文本注释

JAVA 语句用 ; 分号结束。

命名

A、类:首字母大写

B、方法/函数:首字母小写第二个单词首字母大写

C、变量: 首字母小写第二个单词首字母大写

D、常量:全部字母大写

标识符

程序员对程序中的各个元素加以命名时,使用的命名记号,称为标识符。

标识符以字母 下划线(__) 美元符($)开始的一个字符序列,

后可跟 字母,下划线,美元符,数字。

1.1.1、关键字

JAVA关键字(保留字)*

abstract default if private this
boolean do implements protected throw
break double impor public throws
byte else instanceof return transient
case extends int short try
catch final interface statictfp volatile
char finally long strictfp volatile
class float native super while
const for new switch null
continue goto package synchronized

1.1.2、常量

常量:程序执行中,值不可发生改变

变量:在程序执行中,值会发生变化

  • 常量分类

    —— A: 字符串常量 ‘DataScience’

    —— B: 整数常量 123

    —— C: 小数常量 1.23

    —— D: 字符常量 ‘a’,’1’

    —— E: 布尔常量 true ,false
    —— F: 空常量 (null、’’)

public class CL{
    public static void main(String[] args){
        // 字符串常量
        System.out.println("DataScience")

        // 整数常量
        System.out.println(123)

        // 小数常量
        System.out.println(1.23)        

            // 字符串量
        System.out.println("Data")        

            // 布尔常量
        System.out.println(true)

    }
}

1.1.3、变量

变量的申明:

访问[修饰符] 数据类型 变量名称=初始值

变量的分类:
1、按照声明位置:
成员变量:
类的内部,方法的外部定义的变量
局部变量:
方法或代码块的内部定义的变量
区别:
成员变量有默认初始值,局部变量没有
成员变量的作用域在整个类的内部,局部变量在当前方法或代码块中

变量实例:

/**
 * Created by JackFeng on 2019/8/28.
 */

/*
* 常量: 在程序的执行过程中,其值不可以发生改变的量
*
* 常量的分类:
*   A: 字符串常量
*   B: 整数常量
*   C: 小数常量
*   D: 字符常量
*   E: 布尔常量  true ,false
*   F: 空常量
*
* */
public class Variable {
    public static void main(String[] args) {
        // A
        System.out.println("欢迎关注公众号DataScience");

        // B
        System.out.println(12);
        System.out.println(-66);

        // C
        System.out.println(23.56);

        //D
        System.out.println('a');

        // E
        System.out.println(true);
    }
}

1.1.4、数据类型

数据类型 —— Java是强类型语言,针对每一种数据都给出了明确的数据类型。

数据类型分类

  • A:基本数据类型
  • B:引用数据类型 (类、接口、数组)

基本数据类型(以及占用字节数)

  • A、整数
    • byte 1
    • short 2
    • int 4
    • long 8
  • B、浮点数
    • float 4
    • double 8
  • C、字符
    • char 2
  • D、布尔
    • boolean 1

注意

  • A:整数默认是int类型,浮点数默认是double类型
  • B:
    • 定义long类型数据的时候,要加L或者l,建议加L
    • 定义float类型数据的时候,要加F或者f,建议加F

数据类型

整型变量
类型 占用储存空间 表数范围
byte 1字节 -128~127
short 2字节 -2^15~2^15-1
int 4字节 -2^31~2^31-1
long 8字节 -2^63~2^63-1
浮点型变量
类型 占用储存空间 表数范围
float 4字节 -3.403E38~3.403E38
double 8字节 -1.798E308~1.798E308

字符型变量: char 一个字符2字节

布尔型变量: true false

符号常量 final 变量类型 变量名=初始化值

值常量

整型常量、浮点型常量、符号型常量、字符串常量、布尔型常量(true false) 空常量

转义字符 含义
\b 退格(backspace)
\t 水平制表(Tab)
\f 走纸换页,只对打印有效
\n 换行
\r 回车
\ 反斜杠字符
' 单引号字符
" 双引号字符
\ddd 1–3位八进制数所代表的ASCII字符
\uxxxx 1-4位十六进制数所代表的unicode字符

1.1.5、 计算机存储单元

bit(比特位) —–字节(byte)

单位换算:

  • 1B(字节) = 8it
  • 1KB = 1024B
  • 1MB = 1024KB
  • 1GB = 1024MB
  • 1TB = 1024GB
  • 1PB = 1024TB
  • 1ZB = 1024PB

1.1.6、标识符

标识符: 包、类、方法、变量 等起名字的符号

组成规则:
    A:unicode 字符
        数字字符,英文大小写字母,汉字(不建议使用汉字)
    B:下划线 _
    C:美元符 $

注意事项:
    A: 不能以数字开头
    B:不能是Java中的关键字

常见命名规则:
    A:基本要求
        见名知意
    B:常见的命名
        1、包(其实就是文件夹,用于对类进行管理)
            全部小写,多级包.隔开
            EG: com, com.datascience
        2、类
            单个单词首字母大写
            EG:Dog
            多个单词首字母大写
            EG:BigDog
        3、方法和变量
            单个单词首字母小写
            EG: dog
            多个单词组成第二个开始首字母大写
            EG: bigDog,maxAge

1.1.7、运算符优先级

优先级 运算符 结合性
1 () [ ] . 从左向右
2 ! +(正) -(负) ~ ++ – 从右向左
3 / * % 从左向右
4 + (加) -(减) 从左向右
5 《 》 >>> 从左向右
6 <<=>> instanceof 从左向右
7 == != 从左向右
8 & (按位与) 从左向右
9 ^ 从左向右
10 | 从左向右
11 && 从左向右
12 || 从左向右
13 ?: 从右向左
14 = += -= *= /= %= &= |= ^= ~= <<= >>= >>>= 从右向左

1.2、基本类型数据转换

1.2.1、定义变量

变量格式:
    数据类型 变量名 = 初始化值

数据类型:
    byte,short,int,long,float,double,char,boolean

Demo

public class VariableDemo {
/*
* 变量的定义
* */

public static void main(String[] args){
//         定义byte 类型
        byte a = 10;
        System.out.println(10);
        System.out.println(a);

//        定义 short类型
        short b = 11;
        System.out.println(b);

//        定义int类型
        int c = 12;
        System.out.println(c);

//        定义long类型
        long d = 1231L;
        System.out.println(d);


//        定义float类型
        float e = 1.23F;
        System.out.println(e);

//        定义double类型
        double f = 1.23;
        System.out.println(f);

//        定义char类型
        char g = 'a';
        System.out.println(g);

//        定义boolean类型
        boolean h = true;
        System.out.println(h);

        }
}

1.2.2、变量定义的注意事项

package one;

/**
 * Created by JackFeng on 2020/2/22.
 */
public class BianLiang {
    /*
    * 变量定义的注意事项
    *   A: 变量未赋值,不能直接使用
    *   B:变量只在所属的范围内有效(仅在它所在的大括号中有效)
    *   C: 一行可以多个变量(不建议)
    * */
    public static void main(String[] args){

//        定义变量aa、
        int aa = 2020;
        System.out.println(aa);

        {
//            大括号中的就是代码块
            int ab = 131;
            System.out.println(ab);
        }

//        定义多个变量
        int a1, a2;
        a1 =11;
        a2 = 20;

        System.out.println(a1);
        System.out.println(a2);

    }

}

1.2.3、类型转化

package one;

/**
 * Created by JackFeng on 2020/2/25.
 */


/*
*  +:  加法运算符
*
*  运算中,要求参与运算的数据类型必须一致
*
*
*   类型转化:
*       隐式转化
*       强制转化
*           隐式转化:
*               byte,short,char  -- int --long  --float --double
*               byte+ int === int 类型
*           强制转化:
*               目标类型  变量名 = (目标类型)(被转化的数据)
*               建议:数据做运算,最好以结果类型为准(不要随意转化,否则可能损失精度)
*               int a = 10;
*               byte b = 20;
*               int c = a+b
*
*               byte d = (byte)(a + b)
*
*
* */
public class TypeCastDemo {
    public static void main(String[] args) {

//       1、 定义同类型变量
        int a = 11;
        int b = 22;

        int c = a + b;
        System.out.println(c);

//        定义一个 byte 类型 一个int类型
        int a1 = 10;
        byte a2 = 20;
        System.out.println(a1+a2);
    }

}

1.2.4、运算符

1.2.4.1、运算符

运算符: 用于 常量和变量操作的符号

表达式:用运算符号链接起来符合java语法的句子

​ EG: a,b a+b

1.2.4.2、运算符分类

1、算术运算符

+,-,*,/ ,%,++,–

*+,-,,/**

    //    +,-,*,/ 使用
//    定义变量
    int a = 3;
    int b = 4;
    System.out.println(a+b);
    System.out.println(a-b);
    System.out.println(a*b);
    System.out.println(a/b);

//    整数相除 只能得到整数,要想得到小数 必须有浮点数参与运算
    System.out.println(3.0/4);
    System.out.println(3/4.0);

% (取余)

*%*:用于获取 两个数据相除时候的余数

*/*: 用于获取 两个数据相除时候的商

    int a1=3;
    int a2=5;

    System.out.println(a2/a1);
    System.out.println(a2%a1);    

+

+: 加法运算

  • 正常加法运算

    • int a =10;
    • int b = 12;
  • 字符参与加法运算,是拿字符在计算机中存储的数据值来参与运算的

    • “A” 65
    • ‘a’ 97
    • ‘0’ 48
  • 字符串参与加法运算,其实不是做加法,而是字符串的拼接

    • 例如: int a =1; int b =2;

    • System.out.println(“hello”+a)

      • hello1

      System.out.println(a+b+”hello”)

      ​ 3hello

  • 注意 执行顺序(会对结果产生影响): 从左–>右

++,–

++,– : 自增自减,用于对变量+1 或 -1

  • 单独使用:
    • 放在变量前后都可以,结果一样
  • 其它操作:
    • ++ 在后边,先拿变量做操作,然后变量再++
    • ++ 在前边,先变量++,再拿变量做操作
package myOperator;

/**
 * Created by JackFeng on 2020/2/25.
 */

/*
* ++ -- : 自增自减
*
* */
public class OpeartorDemo1 {
    public static void main(String[] args) {

//        定义变量
        int a = 123;
        System.out.println("a:"+a);

//        ++
        int b = a++;
        System.out.println("a:"+a);
        System.out.println("b:"+b);

        int c = ++a;
        System.out.println("a:"+a);
        System.out.println("c:"+c);

    }
}
2、赋值运算符

赋值运算符:

  • 基本赋值运算符:=
  • 扩展赋值运算符:+=,-=,*=,/=,…..
package myOperator;

/**
 * Created by JackFeng on 2020/2/25.
 */
/*
* 赋值运算符:
*   基本的赋值运算符: =
*   扩展的赋值运算符: +=,-=,*=,/= ...
*
* */


public class OpeartorDemo2 {

    public static void main(String[] args) {

//        定义变量
        int a = 25; // 把 25 赋值给int 类型的变量a

//        += 操作
//        拿+= 左边和右边的数据做 加法,然后赋值给左边
        a += 5;
        System.out.println(a);

//        注意: 扩展的赋值运算符,隐含了 强制类型转换
//        有一个变量 a,  a+=5;
//        相当于: a=(a的数据类型)(a+5)

        short s = 1;
        s += 1;
        System.out.println(s);

    }
}
3、关系运算符

关系运算符:

  • ==, !=,>,>=,<,>=
  • 关系运算符结果是 boolean类型.(false/true)

注意事项:

  • 不要把两个== 写成 = (除非你赋值)
4、逻辑运算符

逻辑运算符:

  • 释义:用于链接关系表达式
  • 逻辑运算分类:
    • &,|,^,!
    • &&, ||

&(或)

有false 则false

|(与)

有true则true

^(异或)

相同则false,不同则true

!(非)

true则false,false 则 true

&&

&& 和 & 的结果一样

&& 与 & 的区别:

  • && 有短路效果,左边为false,右边不执行
  • & 左边无论是什么,右边都会执行

||

|| 和 | 的结果一样

|| 与 | 的区别:

  • || 左边为true ,右边不执行
  • | 左边无论是啥,右边都执行
5、三元运算符

三元运算符:

  • 关系表达式?表达式1:表达式2

执行流程:

  • A: 计算关系表达式的值(true/false)
  • B: 结果展示
    • 如果是true,表达式1就是结果
    • 如果是false,表达式2就是结果
       // 三元运算符

        int aa = 10;
        int bb = 20;

        int cc = (aa > bb) ? aa : bb;
        System.out.println("====");
        System.out.println("cc"+cc);

        //输出
        ====
        cc:20

案例:取三个数中的最大值

        // 获取三个数的最大值

        int q = 11;
        int w = 12;
        int e = 22;

        // 先获取两个数据的最大值,然后再和第三个数据比较即可

        int temp = (q > w) ? q : w;
        int max = (temp > e) ? temp : e;
        System.out.println("+++++++++");
        System.out.println("max:"+max);

1.2.5、键盘录入

package myScanner;

/**
 * Created by JackFeng on 2020/2/25.
 */

/*
*
* 键盘录入:
* 如何实现? JDK提供的类Scanner
* 使用步骤:
*       A: 导包
*          import java.util.Scanner;
*          在一个类中顺序: package > import > class
*       B: 创建键盘录入对象
*          Scanner sc = new Scanner(System.in)
*       C: 接受数据
*           int i = sc.nextInt();
*
*
*
* */

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("请输入数据: ");
        int i = sc.nextInt();




        System.out.println("i:"+i);

    }

}

录入数据求和

        // 录入数据 并且求和
        System.out.println("请输入第一个数据: ");
        int aa = sc.nextInt();

        System.out.println("请输入第二个数据: ");
        int bb = sc.nextInt();

        // 数据求和
        int sum = aa + bb;

        System.out.println("sum:"+sum);


        // 比较两个数据是否相等

//        boolean flag = (aa == bb) ? true : false;
        boolean flag = (aa == bb);

        System.out.println(flag);

        // 录入三个数据,三个数据的最大值

        System.out.println("请输入第三个数据: ");
        int cc = sc.nextInt();

        int temp = (aa > bb) ? aa : bb;

        int max = (temp>cc)?temp:cc;

        System.out.println("max:"+max);

1.2.6、流程控制语句

顺序结构

从上往下,依次执行!

选择结构

if语句:

  • if(关系表达式){

    ​ 语句体

    }

  • 执行流程

    • A: 首先计算关系表达式的值,看是true/false
    • B: 如果是true,就执行语句体
    • C: 如果是False,则不执行
    // if 关系表达式

    int    a = 10;
    int b = 20;

    if(a==b){
        System.out.print("a=b")
    }

    int c = 10;

    if(a==c){
        System.out.println("a=c")
    }
  • if(关系表达式){

    ​ 语句体1;

    }else{

    ​ 语句体2;

    }

        // 判断一个数 是偶数还是奇数

        int a = 100;
        // 重新给a赋值
        a = 99;

        if(a%2 ==0){
            System.out.println("a为偶数");
        }else{
            System.out.println("a为奇数");
        }
  • if(关系表达式1){

    ​ 语句体1;

    }else if(关系表达式2){

    ​ 语句体2;

    }

    else{

    ​ 语句体n+1;

    }

 // 多个if 表达式



        int x = 10;
        int y;

        if (x >= 3){
            y = 2 * x + 1;
        } else if (x >= -1 && x<3){
            y = 2 * x;
        }else if (x <= -1){
            y = 2 * x - 1;
        }else {
            y = 0;
            System.out.println("不存在x");
        }

        System.out.println("y"+y);

键盘录入案例比较

    // 键盘录入判断最大值

        Scanner sc = new Scanner(System.in);

        System.out.println("1:");
        int a = sc.nextInt();

        System.out.println("2: ");
        int b = sc.nextInt();

        // 常规比较
        if (a > b) {
            System.out.println("最大值是:"+a);
        }else {
            System.out.println("最大值是:"+b);
        }


        // 用一个变量值接受


        int max;
        if (a > b) {
            max = a;
            System.out.println("max:"+max);
        }else {
            max = b;
            System.out.println("max:"+max);
        }

        // 对变量max 做操作

        max = max + 100;
        System.out.println(max);

1.2.7、选择结构语句

switch

package myOperator;

import java.util.Scanner;

/**
 * Created by JackFeng on 2020/2/26.
 */


/*
* switch语句格式:
*       switch (表达式){
*           case 值1:
*               语句体1;
*           case 值2:
*               语句体2;
*           ...
*           default:
*               语句体n+1;
*               break;
*
* }
*
*
*
* */

public class SwitchDemo {
    public static void main(String[] args) {

        /*
        * 格式解释:
        *   表达式: byte,short,int,char
        *         jdk5 以后 可以是枚举
        *         jdk7 以后 可以是字符串
        *   case后边的值:就是用来和表达式的值进行匹配的内容
        *   break:表示中断的意思
        *   default: 所有值都不匹配的时候(相当于else)
        *
        * */


        // 键盘录入 1-7 判断星期几

        Scanner sc = new Scanner(System.in);

        // 接受数据
        System.out.println("请输入数字 1-7:");
        int weekday = sc.nextInt();

        switch (weekday){
            case 1:
                System.out.println("星期一");
                break;
            case 2:
                System.out.println("星期二");
                break;
            case 3:
                System.out.println("星期三");
                break;
            case 4:

                System.out.println("星期四");
                break;
            case 5:
                System.out.println("星期五");
                break;
            case 6:
                System.out.println("星期六");
                break;
            case 7:
                System.out.println("星期天");
                break;
            default:
                System.out.println("你输入的数据有误");
                break;
        }

    }

}

1.2.8、循环结构语句

1.2.8.1、for

package myOperator;

/**
 * Created by JackFeng on 2020/2/26.
 */

/*
* for循环语句的格式:
*   for(初始化语句;判断条件语句;控制条件语句){
*       循环体语句:
*
* }
*
* */

public class ForDemo {

    public static void main(String[] args) {

//        输出10次 hello
        for (int i=1;i<=10;i++){
            System.out.println("hello"+i);
        }

        // 获取 1-5
        for (int x =1 ;x <=5;x++){
            System.out.println("-----");
            System.out.println(x);
        }

        // 获取 5-1
        for (int x = 5; x >= 1; x--) {
            System.out.println("======");
            System.out.println(x);
        }

        // 1-5 求和

        //初始化值为0

        int sum = 0;
        for (int x =1;x<=5;x++){
            sum = sum + x;
//            sum += x;
            System.out.println("累加值为:"+sum);

        }
        System.out.println("sum"+sum);

    }
}


1-100 偶数和

        // 结果:2550
        int s = 0;
        for (int x =1;x<=100;x++){
            if (x%2 ==0){
                s += x;
            }
        }
        System.out.println("1-100偶数求和为:"+s);

水仙花

        //经典案例 水仙花数
        // EG: 153
        // 个位: 153%10
        // 十位: 153/10%10
        // 百位: 153/10/10%10
        int count = 0;

        for (int x=100;x<=999;x++){
            int gw =x % 10;
            int sw =x/10 % 10;
            int bw =x/10/10 % 10;
            if ((gw*gw*gw +sw*sw*sw + bw*bw*bw )==x){
                System.out.println(x);
                count++; //统计次数
            }
        }
        //输出统计值
        System.out.println(count);

1.2.8.2、while

package myOperator;

/**
 * Created by JackFeng on 2020/2/26.
 */
public class WhileDemo {

    public static void main(String[] args) {

        // 输出10次 你好
        // for 实现

        for (int i =1;i<=10;i++){
            System.out.println("你好");
        }

        // while 实现

        int s = 1;
        while (s<=10){
            System.out.println("Nihao");
            s++;
        }


    }

}

1.2.8.3、do…while

package myOperator;

/**
 * Created by JackFeng on 2020/2/26.
 */
public class DoWhileDemo {

    public static void main(String[] args) {
        // 输出10次 HI

        for (int i =1;i<=10;i++){
            System.out.println("Hi");
        }

        // do while 改写

        int x = 1;
        do {
            // 循环体语句
            System.out.println("HI hi");
            // 控制条件语句
            x++;
        }
        // 判断体语句
        while (x <= 10);



    }

}

1.2.8.4、 三种循环语句区别

A: do…while 循环至少执行一次循环体

B: for和 while 必须判断条件成立才执行循环体

package myOperator;

/**
 * Created by JackFeng on 2020/2/26.
 */
public class XunDemo {

    public static void main(String[] args) {

        int x = 3;
        while(x <3){
            System.out.println("while 循环体");
            x++;
        }


        int y = 3;
        do {
            System.out.println(" do while 循环ti ");
            y++;
        } while (y < 3);
    }
}

for 和 while 区别

for循环结束后,初始化变量不可被使用。

while 循环结束后,初始化变量可以被使用。

推荐使用顺序:

  • for
  • while
  • do…while
    // for 和 while 的区别

    public static void main(String[] args) {

        //for
        for (int i = 0; i <5 ; i++) {
            System.out.println("这里是for循环");
        }
//        System.out.println("i:"+i); 这里是调用不了的

        //while

        int x =0;
        while (x<5){
            System.out.println("while循环");
            x++;
        }
        System.out.println("x:"+x);


    }

1.2.9、跳转控制语句

Break(中断)

break:中断

使用场景:

  • A:switch语句中
  • B:循环中

注意:

  • 离开场景,将无意义。

作用:

  • 用于结束循环
package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class BreakDemo {

    public static void main(String[] args) {

        for (int i = 0; i <4 ; i++) {
            System.out.println("这是个正常的循环");

        }

        System.out.println("============");
        for (int i = 0; i <4 ; i++) {

            if (i==1){
                break;
            }
            System.out.println("这是加入break控制的循环");
        }

    }
}

Continue(继续)

continue:继续

使用场景:

  • 循环中

作用:

  • 结束一次循环,进入下一次循环。
package com.data.it;

import java.sql.SQLOutput;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class BreakAndContinueDemo {
    public static void main(String[] args) {

        for (int i = 0; i <=10 ; i++) {

//            break:结束整个循环

            if (i == 2){
                break;
            }
            System.out.println("B And C");

//            continue 结束本次循环,继续下一次循环
            if (i==3){
                continue;
            }
            System.out.println("C === A");

        }
    }
}

1.3、Random

Random:用于产生随机数

使用步骤:

  • A:导包
    • import java.util.Random;
  • B:创建对象
    • Random r = new Random();
  • C:获取随机数
    • int number = r.nextInt(10)
    • 数据范围:[0,10) 包括0,但不包括10
package com.data.it;


import java.util.Random;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class RandomDemo {

    public static void main(String[] args) {
        //创建对象
        Random r = new Random();

        // 获取随机数
        int n = r.nextInt(10);

        System.out.println("n:"+n);

        for (int i = 0; i <10 ; i++) {
            int num = r.nextInt(10);

            System.out.println("第"+i+"次随机数结果为:"+num);

        }


        // 如何获取100 - 1之间的随机数

        int ii = r.nextInt(100);// [0,99]
        int T = r.nextInt(100)+1;// +1 即可


    }


}


猜数字游戏

package com.data.it;

import java.util.Random;
import java.util.Scanner;

/**
 * Created by JackFeng on 2020/3/1.
 */

/*
* 猜数字游戏:
*       系统产生一个 1-100 的数字,猜出这个数字是多少
*
* 分析:
*   A:系统产生一个1-100之间的随机数
*       Random r = new Random();
*       int number = r.nextInt(100)+1;
*   B: 键盘录入要猜的数据
*   C: 比较这两个数据的大小
*       大了:提示大了
*       小了:提示小了
*       相等:猜中了
*   D:多次猜数据,而我们不知道猜多少次?
*       while(true){循环体语句};
*
*
* */


public class RandomNumDemo {
    public static void main(String[] args) {


//      产生1-100随机数
        Random r = new Random();
//        获取随机数
        int i = r.nextInt(100)+1;



//        判断是否猜中 多次猜数据
        // 录入的数据 要放在判断里 否则永远也猜不中
        while (true) {

            //        键盘录入
            Scanner s = new Scanner(System.in);

//        获取输入数据
            System.out.println("请输入你要猜的数据:");
            int g = s.nextInt();

            if (g>i){
                System.out.println("你猜的"+g+"大了");
            }else  if (g<i){
                System.out.println("你猜的"+g+"小了");
            }else {
                System.out.println("恭喜你猜中了");
                break;
            }
        }



    }
}

1.4、数组

数组:存储同一种数据类型的多个元素的容器

取值:

  • 数组名 【索引】

定义格式:

  • A:数据类型[] 数组名;(推荐方式)
  • B:数据类型 数组名[];
  • 案例:
    • int[] arr; 定义int类型的数组,名称为 arr
    • int arr[];定义int类型的变量,变量名为arr数组

数组初始化:

  • A:数组开辟内存空间,为数组中的每个元素赋值
  • B:数组初始的方式:
    • a:动态初始化 只给出长度,系统给初始化值
    • b:静态初始化 给出初始值,由系统决定长度

动态初始化:

  • 数据类型[] 数组名 = new 数据类型[数组长度];

静态初始化:

  • 数据类型[] 数组名 = new 数据类型[]{元素1,元素2….};
  • 简化格式:
    • 数据类型[] 数组名 ={元素1,元素2,…}

动态初始化

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */



public class MyArrayDemo {

    public static void main(String[] args) {
        //数据类型[] 数组名 = new 数据类型[数组长度];
        int[] arr = new int[3];

        // 释义
        /*
        * 左边:
        *   int:说明数组中的元素类型是 int 类型
        *   []:  说明是个数组
        *   arr: 数组名称
        *
        * 右边:
        *   new : 为数组申请内存分配空间
        *   int: 数组中的元素是int类型
        *   []: 数组
        *   3: 数组的长度----数组中元素的个数
        * */

        //输出数组名
        System.out.println("arr"+arr); //[I@4554617c

        // 获取的是地址值,如何获取数组中的元素值
        // 数组中的元素都是有编号的,从0 开始,最大编号是 数组的长度-1
        // 索引 arr[0]
        // 取值:  数组名 配合 元素编号
        // 访问格式:数组名[索引]

        System.out.println(arr[0]);  //0
        System.out.println(arr[1]); // 0
        System.out.println(arr[2]);  //0

//        赋值
        arr[0] = 100;
        arr[2] = 200;

        System.out.println("=====");

        System.out.println(arr); // 001

        System.out.println(arr[0]); //100
        System.out.println(arr[1]); // 0
        System.out.println(arr[2]); //200


        // 指向一个数组

//         arr1 数组
        int[] arr1 = new int[3];
        System.out.println(arr1);
        System.out.println(arr1[0]);
        System.out.println(arr1[1]);
        System.out.println(arr1[2]);


        int[] arr2 = arr1;
        arr1[0] =111;
        arr1[1] =222;
        arr1[2] =123;

        System.out.println("=============");

        System.out.println(arr1);
        System.out.println(arr1[0]);
        System.out.println(arr1[1]);
        System.out.println(arr1[2]);


        System.out.println(arr2);
        System.out.println(arr2[0]);
        System.out.println(arr2[1]);
        System.out.println(arr2[2]);




    }
}

静态初始化

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */


public class ArraryDemo {

    public static void main(String[] args) {

        int[] arr = new int[]{1,2,3};

        int[] arr1 = {1, 2, 3};

        System.out.println(arr);
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);


//
        System.out.println("----------");
        System.out.println(arr1);
        System.out.println(arr1[0]);
        System.out.println(arr1[1]);
        System.out.println(arr1[2]);


    }
}

常见小问题

小问题:

  • ArrayIndexOutOfBoundsException: 数组索引越界异常
    • 原因 我们访问了不存在的索引
  • NullPointerException:空指针异常
    • 原因 数组已经不在指向堆内存的数据了,还使用数组名去访问数组中的数据

数组遍历练习

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class ArrayTest {
    public static void main(String[] args) {
        // 定义数组
        int[] arr = {1, 2, 3, 4, 5, 6};

        // 通过for循环遍历输出 ,调用 数组属性:length 
        // 格式: 数组名.length

        for (int i = 0; i <arr.length ; i++) {
            System.out.println(arr[i]);
        }


    }
}

取最值

思路:

  • A:先拿数组中的一个元素做参照物
  • B:遍历数组,让后边所有元素依次和参照物进行比较,如果元素比参照物大,就留下
  • C:整个循环遍历比较,留下的就是最大值
package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class ArrayTest1 {

    public static void main(String[] args) {
        // 取最大值
        int[] arr = {1, 2, 3, 55, 22, 10};

        // 定义一个参照值
        int max = arr[0];

        // 循环遍历整个数组

        for (int i = 1; i <arr.length ; i++) {
            if (arr[i]>max){
                max = arr[i];
            }
        }
        System.out.println("最大值为:"+max);


    }
}

二维数组


二维数组: 元素为一堆数组的数组



定义格式:

- A:数据类型[ ] [ ] 数组名; (推荐的方式)
- B:数据类型 数组名[ ] [ ]
- C:数据类型[ ] 数组名[ ]

初始化:

- A: 动态初始化
  - 数据类型[ ] [ ] 数组名 = new 数据类型[m] [n];
  - m 表示的是 二维数组中一维数组的个数
  - n  表示的是 一维数组中的元素个数
- B: 静态初始化
  - 数据类型[ ] [ ] 数组名 = new 数据类型[ ] [ ] {{元素…},{元素….}}
  - 简化格式:
    - 数据类型[ ] [ ] 数组名 = {{1,…},{2….},{3….}}

取值:

- *二维数组名配合索引可以获取到每一个一维数组*  【**arr[索引]**】
- *一维数组配合索引名可以获取到数组中的元素*【**arr[索引] [索引]**】

二维数组取值

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class Array2Test {
    public static void main(String[] args) {

        //数据类型[] [] 数组名 = {{元素..},{元素...}}


        int[][] arr = {{1, 2, 3}, {1, 3, 6}, {2, 3, 6}};
        //
//        System.out.println(arr);
//        System.out.println(arr[0]);
//        System.out.println(arr[0][0]);

        // 遍历二维数组

        // 第一个数组的元素
        for (int i = 0; i <arr[0].length ; i++) {

            System.out.println(arr[0][i]);

        }

        System.out.println("==========");
        // 第二个数组的元素
        for (int i = 0; i <arr[2].length ; i++) {

            System.out.println(arr[0][i]);

        }


        // 优化循环二维数组

        System.out.println(" -----------");
        // 二维数组 arr.length 就是有几个 一维数组
        for (int i = 0; i < arr.length ; i++) {
            for (int j = 0; j <arr[i].length ; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println("====");

        }
    }
}

1.5、函数

方法使用

方法: 特定功能的代码块

方法定义格式:

  • 修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2 ..){

    ​ 方法体;

    ​ return 返回值;

    }

格式解释:

  • A:修饰符 public static
  • B:返回值类型 限定返回值的数据类型
  • C:方法名 方便我们调用方法的名字
  • D:参数类型 用于限定调用方法时传入数据的类型
  • E:参数名 用于接收调用方法时传入的数据变量
  • F: 方法体 完成功能代码
  • G:return 结束方法,并且把返回值带给调用者

方法明确:

  • A:返回值类型 明确功能结果的数据类型
  • B:参数列表 明确有几个参数,以及参数的数据类型

方法调用:(有明确返回值的调用)

  • A:单独调用 没有意义
  • B:输出调用,有意义,但是不够好(因为我想要拿结果进一步操作)
  • C:赋值调用

方法调用:(void修饰的方法)

  • 如果一个方法没有明确的返回值,也不能空开返回值,用void表示该方法无返回值类型
  • 只能输出调用。

求和方法

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class SumTest {

    public static void main(String[] args) {

        //调用sum
//        单独调用 无意义
//        sum(10, 20);

        // 输出调用,有意义,不完美
//        System.out.println(sum(10,20));


        // 赋值调用,常用操作。
        int i = sum(10, 20);
        System.out.println(i);
        System.out.println(i+1);

        // 对i 进行操作
        int j = sum(10,20)+10;
        System.out.println(j);



    }
    /*
    * 两个明确:
    *       返回值:  int
    *       参数列表: int a , int b
    *
    *
    * */

    public static int sum(int a , int b ){
        int c = a + b;
        return  c;
    }

}


键盘录入两个数据判断是否相等

package com.data.it;

import java.util.Scanner;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class MethodTest {
    public static void main(String[] args) {

//        创建键盘录入
        Scanner sc = new Scanner(System.in);
//        接收数据
        System.out.println("请输入第一个数据:");
        int x = sc.nextInt();

        System.out.println("请输入第二个数据:");
        int y = sc.nextInt();

//        调用方法
        boolean b = bijiao(x, y);

        System.out.println(b);

    }

    /*
    * 求两个值是否相等:
    *   返回值: boolean
    *   参数列表: int a,int b
    *
    * */


    public static  boolean bijiao(int a , int b ){
        if (a==b){
            return true;
        }else {
            return false;
        }
    }

}

水仙花数

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class MethodTest1 {

    public static void main(String[] args) {
        //调用方法
        printFlower();
    }

    /*
    * 水仙花数打印到控制台方法
    *
    *  两个参数:
    *       返回值类型:void
    *       参数列表: 无参数
    *
    * */

    public  static  void printFlower(){

        for (int i = 100; i <1000 ; i++) {
            int g = i%10;
            int s = i/10%10;
            int b = i/10/10%10;

            if (g*g*g + s*s*s + b*b*b == i){

                System.out.println(i);
            }

        }

    }

}

方法重载

方法重载: 在同一个类中,出现了方法名相同

不能出现参数名以及参数条件一致的方法

特点:

  • 方法名相同,参数不同
  • 参数不同
    • 参数数量不同
    • 参数个数不同

注意:在调用方法的时候,java虚拟机会通过参数列表的不同来区分同名的方法。

比较两个数据是否相等

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class MethodTest2 {
    public static void main(String[] args) {
        System.out.println(compare(10,10));
        System.out.println(compare(10L,10L));
        System.out.println(compare((byte) 10,(byte)20));
        System.out.println(compare((short) 10,(short) 20));
    }

    //byte

    public static boolean compare(byte a , byte b){
        System.out.println("byte");
        return a == b;
    }

    //short

    public static boolean compare(short a , short b){
        System.out.println("short");
        return a == b;
    }

    //int

    public static boolean compare(int a , int b){
        System.out.println("int");
        return a == b;
    }

    //long

    public static boolean compare(long a , long b){
        System.out.println("long");
        return a == b;
    }



}


形式参数

如果方法的参数是基本数据类型:

​ 形式参数的改变不影响实际参数

如果方法的参数是引用数据类型:

​ 形式参数的改变直接影响实际参数

数组遍历

package com.data.it;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class ArrayDo {
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("第一种方式");
        printArray(arr);

        System.out.println("第二种方式");
        printArray1(arr);


    }


    /*
    * 两个明确:
    *       返回类型: void
    *       参数列表: int[] arr
    * */

    public static void printArray(int[] arr){
        for (int i = 0; i <arr.length ; i++) {
            System.out.println(arr[i]);
        }
    }
    public static void printArray1(int[] arr){

        // 输出为这样的 [1,2,3,4,5]
        System.out.print("[");
        for (int i = 0; i <arr.length ; i++) {
            if (i==arr.length-1){
                System.out.println(arr[i]+"]");
            }else {
                System.out.print(arr[i]+", ");
            }
        }
    }


}

1.6、断点调试

断点调试的作用:

​ A: 查看程序的执行流程

​ B: 调试程序

断点:

​ – 标记

哪里需要点哪里 需加在有效的地方

1.7、基础练习

不死神兔计算

package myTest;

/**
 * Created by JackFeng on 2020/3/1.
 */
public class Test {
    public static void main(String[] args) {
        // 20个月 兔子的对数
        // 1,1,2,3,5....

//        定义数组
        int[] arr = new int[20];

        // 给数组赋值
        arr[0] = 1;
        arr[1] = 1;

        // 找规律赋值
        for (int i = 2; i <arr.length ; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        //输出结果
        System.out.println("第20个月兔子的对数是:"+arr[19]);

    }
}

评委评分

需求:

​ 在编程竞赛中,有6个评委为参赛选手打分,分数为0-100的整数分。

​ 选手最后的得分为,去掉一个最高分与最低分,剩下4个评委的平均值

分析:

  • A:定义一个长度为6的数组
  • B:键盘录入评委的分数
  • C:写方法实现最高分、最低分
  • D:写方法求评委分数和
  • E:平均分:(和-最高分-最低分)/(arr.length-2)
  • F:输出平均分
package myTest;

import java.util.Scanner;

/**
 * Created by JackFeng on 2020/3/2.
 */
public class Test1 {
    public static void main(String[] args) {


        //定义数组
        int[] arr = new int[6];

        //键盘录入

        Scanner sc = new Scanner(System.in);

        //键盘录入评委分数

        for (int i = 0; i <arr.length ; i++) {

            //接受数据
            System.out.println("请输入第 "+(i+1)+"个评委给出的分数");
            int score = sc.nextInt();
            arr[i] = score;
        }

        //调用方法
        int max = getMax(arr);
        int min = getMin(arr);

        int sum = sum(arr);

        // 求平均分
        int avg = (sum - max - min) / (arr.length - 2);

        System.out.println("该选手的最终得分是:"+avg);



    }


    //最高分
    /*
    * 两个明确:
    *      返回值类型: int
    *       参数列表: int [] arr
    *
    *
    * */
    public static  int getMax(int[] arr){
        //定义参照物
        int max = arr[0];

        for (int i = 1; i <arr.length ; i++) {
            if (arr[i]>max){
                max = arr[i];
            }

        }
        return max;
    }


    // 最低分
    public static  int getMin(int[] arr){
        //定义参照物
        int min = arr[0];

        for (int i = 1; i <arr.length ; i++) {
            if (arr[i]<min){
                min = arr[i];
            }

        }
        return min;
    }

    // 求和
    public static  int sum(int[] arr){
        // 定义求和变量
        int sum = 0;
        for (int i = 0; i <arr.length ; i++) {
            sum += arr[i];
        }
        return sum;
    }


}

键入数组反转

需求:

  • 1、键盘录入5个int的数据存在arr中
  • 2、定义方法将arr数组中的内容反转
  • 3、定义方法对反转后的数组进行遍历
package myTest;

import java.util.Scanner;

/**
 * Created by JackFeng on 2020/3/2.
 */


public class Test2 {
    public static void main(String[] args) {


        int[] arr = new int[5];

        Scanner sc = new Scanner(System.in);

        for (int i = 0; i <arr.length ; i++) {
            System.out.println("请输入"+(i+1)+"个元素值:");
            int number = sc.nextInt();
            arr[i] = number;
        }

        printArray(arr);


        // 反转 arr
        reverse(arr);
        System.out.println("反转后");
        printArray(arr);

    }

    //遍历数组

    public  static void printArray(int[] arr){

        System.out.print("[");
        for (int i = 0; i <arr.length ; i++) {

            if (i==arr.length-1){
                System.out.println(arr[i]+"]");
            }else{
                System.out.print(arr[i]+", ");
            }

        }


    }

    // 反转数组
    public  static  void  reverse(int[] arr){
        for(int start =0, end= arr.length-1; start<=end;start++,end--){
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;

        }
    }

}

评论