第二章----基本语法

1、关键字和保留字

在这里插入图片描述
除了上述关键字,Java还有以下特殊的:true,false,null

2、标识符

2.1、标识符的使用

凡是自己可以起名的地方都叫标识符
如:类名、变量名、方法名、接口名、包名。。。

2.2、标识符的命名规则

英文字母大小写,0-9,_,$ 组成
数字不能开头
不可以使用关键字和保留字,可以包含
区分大小写,长度无限制

2.3、标识符的命名规范

包名:xxxyyyzzz
类名、接口名:XxxYyyZzz
变量名、方法名:xxxYyyZzz
常量名:XXX_YYY_ZZZ

注意:
起名时,见名知意
java采用unicode字符集,因此也可以使用汉字,但不建议使用

3、变量

定义变量: 数据类型 变量名 = 变量值
说明:
 变量必须先声明后使用
 变量都有作用域,出了作用域后就失效了
 同一个作用域内,变量名需唯一

3.1、变量分类

在这里插入图片描述
在这里插入图片描述

3.2、整数类型:byte、short、int、long

在这里插入图片描述

3.3、浮点类型:float、double

在这里插入图片描述

要解释浮点型,需要读计算机组成原理

3.4、字符类型:char

char 型数据用来表示通常意义上“字符”(2字节)

  • 定义char型变量,通常使用一对’’,内部只能写一个字符
  • 表示方式:
    1. 声明一个字符
    2. 转义字符
    3. 直接使用unicode值
char c3 = '9';
char c3 = '\n';
char c3 = '\u000a';

3.5、布尔类型:boolean

true,false
常用做判断使用

3.6、基本数据类型转换

3.6.1、自动类型提升

容量小的数据类型 与 容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。
byte、char、short --> int --> long --> float --> double

byte,short,char之间不会相互转换,他们三者在计算时首先转换为int类型。

3.6.2、强制类型转换

使用时要加上强制转换符:(),但可能造成精度降低或溢出,格外要注意。

3.7、java 新特性:数据分隔

int a = 12_3456_7890;

4、运算符

4.1、算数运算符

在这里插入图片描述
/ :说明

int num1 = 12
int num2 = 5

int result1 = num1/num2;//2
double result2 = num1/num2;//2.0

double result3 = num1/(num2 + 0.0)//2.4;
double result4 = (double)num1/num2//2.4

% :说明

结果的符号与被模数的符号相同
开发中经常使用 % 来判断能否被除尽的情况

12 % 5 		//2
12 % -5 	//-2
-12 % 5 	//2
-12 % -5 	//-2

100 % 7 = 100 -(100/7)*7 = 2
120 % 9 = 120 - (120/9)*9 = 3

++ – : 说明

++ : 先自增1,后运算
后++ : 先运算,后自增1
int a1 = 10;
int b = ++a;//b=11,a=11
int a2 = 10;
int c = a++;//c=10,a=11

int a3 = 10;
++a3;// a3++;
int d = a3; //d=11,a3=11

注意:
short s1 = 10;
//s1 = s1 + 1;//编译失败
s1 = (short)(s1 + 1);//正确
s1++; //自增1不会改变本身的变量类型

byte bb =127;
bb++;//-128

int a = 10;
a = a++;
a = ++a;

在这里插入图片描述在这里插入图片描述

4.2、 赋值运算符

= : 赋值符号
int i1 = 10;
int j1 = 10;

//连续赋值
int i2,j2;
i2 = j2 = 10;

int 13 = 10,j3 = 20;

**********************************

+=,-+,*=,/=,%=

int n1 = 10;
n1 += 2; // n1 = n1 + 2;

short s1 = 10;
//s1 = s1 + 2; //编译失败(自动类型转换)
s1 += 2;//不会改变变量的数据类型

4.3、比较运算符

==、!=、<、>、<=、>=、instanceof
instanceof:检查是否是类的对象"hello" instanceof String //true
比较运算符的结果都是 boolean 型

4.4、逻辑运算符

& 逻辑与
| 逻辑或
! 逻辑非
&& 短路与
|| 段落或
^ 逻辑异或

逻辑运算符操作的都是布尔类型的变量
短路 运算符当条件一不满足时,就不会判断条件二,不过运算的结果是相同的

4.5、位运算符

<<左移一般是整型变量,高位溢出,低位补零。当移动到符号为上数值为1时数据将变为负数3<<2=12
>>右移高位补符号位,低位溢出
>>>无符号右移高位补零,低位溢出
&
|
!
^

m = k ^ n = (m ^ n) ^ n

21 << 2
21 << 3
21 << 27

12 & 5
12 | 5
12 ^ 5
~6

4.6、三元运算符

(条件表达式) ?表达式1 : 表达式2
表达式1 和 表达式2 需要是同一个类型

5、流程控制

5.1、分支结构

5.1.1、if-else
if(){}
if(){}else{}
if(){}else if(){}else{}

条件表达式关系
互斥
交集:需要考虑顺序问题
包含:被包含的需要写在上面

5.1.2、switch-case
switch(表达式){
case xxx:
	break;
case yyy:
	break;
default:
	break;

}

表达式类型
byte,short,char,int,枚举(5.0),String(7.0)

5.2、循环结构

5.2.1、for、while、do-while
for(初始化;循环条件(boolean;迭代条件){循环语句}

 public void forMethod(int m,int n){
     int max = ( m >= n ) ? m : n;
     for(int i = max; i < m*n; i++){
         if (i%m == 0 && i%n ==0){
             System.out.println("最小公倍数" + i);
             break;
         }
     }

     int min = (m <= n) ? m : n;
     for (int i = min; i >= 1;i--){
         if (m % i == 0 && n % i ==0){
             System.out.println("最大公约数" + i);
             break;
         }
     }
 }


初始化
while(循环条件){
	循环语句
	迭代条件
}

5.2.2、无限循环

while(true){}
for(;;){}

5.2.3、嵌套循环
/*
输出如下图形
******
******
******
******
*/
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 6; j++) {
        System.out.print("*");
    }
    System.out.println();
}

/*
输出如下图形
*
**
***
****
*****
*/
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}

/*
输出如下图形
*****		1		5		i + j = 6   j = 6 - i
****		2		4
***			3		3
**			4		2
*			5		1
*/
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= (6-i); j++) {
        System.out.print("*");
    }
    System.out.println();
}
/*

    * 			1		4 " "		1*		5行 i[0,5)
   * * 			2		3 " "		2*		" "	j[0,4-i)
  * * * 		3		2 " "		3*		*	k[0,i+1)
 * * * * 		4		1 " "		4*
* * * * * 		5		0 " "		5*

 * * * * 		1		1 " "		4*		4行 i[0,4)
  * * * 		2		2 " "		3*		" " j[0,i+1)
   * * 			3		3 " "		2*		*	k[0,4-i)
    * 			4		4 " "		1*



*/

for (int i = 0; i < 5; i++){
    for (int j = 0; j < 4 -i; j++){
        System.out.print(" ");
    }
    for (int k = 0; k < (i + 1); k++){
        System.out.print("* ");
    }
    System.out.println();
}

for (int i = 0; i < 4; i++){
    for (int j = 0; j < i + 1; j++){
        System.out.print(" ");
    }
    for (int k = 0; k < 4 - i; k++){
        System.out.print("* ");
    }
    System.out.println();
}
九九乘法表
1*1=1	
2*1=2	2*2=4	
3*1=3	3*2=6	3*3=9	
4*1=4	4*2=8	4*3=12	4*4=16	
5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81

for (int i = 0; i < 9; i++) {
    for (int j = 0; j < i + 1; j++) {
        System.out.print( (i+1) + "*" + (j + 1) + "=" + (i + 1) * (j + 1) + "\t");
    }
    System.out.println();
}
5.2.4、break和continue和return的使用
breakswitch-case、循环结构
continue循环结构中
return结束一个方法

附录

键盘录入

Scanner
Scanner sc = new Scanner(System.in);
//int
int num = sc.nextInt();
//string
next();
nextLine();
//double
nextDouble()
//boolean
nextBoolean();
BufferedReader
    /**
     * CMD 控制台
     */
    @Test
    public void test02(){
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            String cmdstr = bf.readLine();
            Process proc = Runtime.getRuntime().exec(cmdstr);
        } catch (IOException ioException) {

        }
    }
随机数
    @Test
    public void test01(){
        Random random = new Random();
        while (true) {
            //产生一个[0,2)的随机整数
            int i = random.nextInt(2);
            System.out.println(i);
        }
    }


    /**
     * Math.random:产生一个[0-1)之间的随机数
     *
     * [1-5]
     * [0,1)--> [1,6) 取整
     * [0,1)*5 --> [0,5) + 1 --> [1,6)
     * 1 + r * (5-1 +1)
     *
     *
     * 随机数:[A,B] = A + r * ( B - A + 1 )
     */

字符串

split
    @Test
    public void test1(){
        String str1 = "   ";
        System.out.println(Arrays.toString(str1.split(",")));

        System.out.println("**********华丽底线**********");

        String str2 = "a,b|c_,d|e_f.g";
        System.out.println(Arrays.toString(str2.split("\\,")));
        System.out.println(Arrays.toString(str2.split("\\|")));
        System.out.println(Arrays.toString(str2.split("\\.")));
        System.out.println(Arrays.toString(str2.split("\\_")));

        System.out.println("**********华丽底线**********");

        String str3 = "a|";        //[a]
        String str4 = "a||";       //[a]
        String str5 = "a||b|";     //[a, , b]
        String str6 = "a||b|||||";    //[a, , b]
        String str7 = "a||c";      //[a, , c]
        String str8 = "|a||c|||";     //[, a, , c]
        String str9 = "||a||c||||";    //[, , a, , c]


        /**
         *  If n is zero then the pattern will be applied as many times as possible,
         *  the array can have any length, and trailing empty strings will be discarded.
         */
        //默认为0 :数组可以有任意长度,并且尾随的空字符串将被丢弃。
        System.out.println(Arrays.toString(str3.split("\\||")));
        System.out.println(Arrays.toString(str4.split("\\||")));
        System.out.println(Arrays.toString(str5.split("\\||")));
        System.out.println(Arrays.toString(str6.split("\\||")));
        System.out.println(Arrays.toString(str7.split("\\||")));
        System.out.println(Arrays.toString(str8.split("\\||")));
        System.out.println(Arrays.toString(str9.split("\\||")));
        System.out.println(Arrays.toString(str3.split("\\||",0)));
        System.out.println(Arrays.toString(str4.split("\\||",0)));
        System.out.println(Arrays.toString(str5.split("\\||",0)));
        System.out.println(Arrays.toString(str6.split("\\||",0)));
        System.out.println(Arrays.toString(str7.split("\\||",0)));
        System.out.println(Arrays.toString(str8.split("\\||",0)));
        System.out.println(Arrays.toString(str9.split("\\||",0)));


        System.out.println("**********limit=1**********");
        // limit 参数控制应用模式的次数,因此会影响结果数组的长度。
        // 如果限制 n 大于零,则模式将最多应用 n - 1 次,数组的长度将不大于 n,
        // 并且数组的最后一个条目将包含最后一个匹配分隔符之外的所有输入
        System.out.println(Arrays.toString(str3.split("\\||",1)));
        System.out.println(Arrays.toString(str4.split("\\||",1)));
        System.out.println(Arrays.toString(str5.split("\\||",1)));
        System.out.println(Arrays.toString(str6.split("\\||",1)));
        System.out.println(Arrays.toString(str7.split("\\||",1)));
        System.out.println(Arrays.toString(str8.split("\\||",1)));
        System.out.println(Arrays.toString(str9.split("\\||",1)));


        System.out.println("**********limit=-1**********");
        // 如果 n 为非正数,则该模式将尽可能多地应用,并且数组可以具有任意长度。
        System.out.println(Arrays.toString(str3.split("\\||",-1)));
        System.out.println(Arrays.toString(str4.split("\\||",-1)));
        System.out.println(Arrays.toString(str5.split("\\||",-1)));
        System.out.println(Arrays.toString(str6.split("\\||",-1)));
        System.out.println(Arrays.toString(str7.split("\\||",-1)));
        System.out.println(Arrays.toString(str8.split("\\||",-1)));
        System.out.println(Arrays.toString(str9.split("\\||",-1)));

    }
String的值传递机制
    /**
     * equals
     * ==
     * 值传递机制
     */
    @Test
    public void test1(){
        String str1 = "calc"; //常量池中,返回常量池中地址引用
        String str2 = str1; //浅拷贝
        String str3 = new String("calc"); //堆区,动态分配,自动回收,System.gc
        String str4 = "calc";

        System.out.println(str1.equals(str2));
        System.out.println(str1.equals(str3));
        System.out.println(str1.equals(str4));

        System.out.println(str1 == str2);//地址相同 true
        System.out.println(str2 == str3);//地址不同 false
        System.out.println(str3 == str4);//地址不同 false
        System.out.println(str4 == str1);//常量池中 true

        //字符串是不可变的,同基本数据类型一致有"副本机制"
        change(str2);
        System.out.println("str2" + "---" + str2 );
    }

    public void change(String str){
        str = "zs";
        System.out.println("change" + "---" + str);
    }
length()、indexOf()
    /**
     * length()
     * indexOf()
     *
     */
    @Test
    public void test2(){
        String str = "azsfadfzssdfafasdfa zs adfadsfzsasdfafzs";
        int ch = str.length(); // 字符串长度

        int pos1 = str.indexOf("zs");//第一次出现的位置
        int pos2 = str.indexOf("123"); //-1
        int pos3 = str.indexOf("zs",pos1 + 2);//第二次出现的位置
        System.out.println(pos3);
        System.out.println("change" + "---" + str);

        System.out.println("***********找出所有位置***********");
        int pos;
        for (pos = 0;;pos+="zs".length()){
             pos = str.indexOf("zs", pos);
             if (pos == -1){
                 break;
             }
            System.out.println(pos);
        }


//        for(int pos = 0; pos != -1; pos = str.indexOf("zs",pos)){
//
//            System.out.println(pos);
//
//            pos +="zs".length();
//
//        }

    }
charAt()、subString()

    /**
     * 挖掘子串,QQ号码截取
     * charAt
     * subString
     */
    @Test
    public void test3(){
        String str = "asfsdfsdf   asdfadsf   adasdf   2020299870@qq.com  asdfasdf";
        int pos = str.indexOf("@");
        System.out.println(pos);
        if (pos != -1){
            int headpos = 0;
            int backpos = 0;
            for(int i = pos;i <= str.length()-1 && str.charAt(i) != ' ';i++){
                backpos = i + 1;
            }
            for(int i = pos;i >= 0 && str.charAt(i) != ' ';i--){
                headpos = i;
            }
            System.out.println(str.substring(headpos,backpos));
        }
    }
lastIndexOf()、toUpperCase()、toLowerCase()
   /**
     * lastIndexOf
     *
     * toUpperCase
     * toLowerCase
     *
     * 字符 +
     * concat
     */
    @Test
    public void test4(){
        String str = "a %% asfsd黄色fsdf 黄色  asd黄色fadsf 黄色  adasdf   2020299870@qq.com  asdfa % sdf";
        System.out.println(str.lastIndexOf("%"));

        System.out.println(str.toUpperCase());
        System.out.println(str.toLowerCase());

        //首字母大写
        System.out.println(str.substring(0, 1).toUpperCase().concat(str.substring(1)));

        System.out.println(str.replaceAll("黄色","**"));

    }
trim()、startsWith()、contains()、format()、hashCode()
    /**
     * trim: 去除前后空格
     *
     * startsWith : 是否以某个字符开头
     * contains : 是否包含
     *
     * format
     *
     * 根据字符 数组初始化
     * 根据byte数组初始化
     *
     * hashCode : 字符串的唯一标识
     * */
    @Test
    public void test5(){
        String str = "    a %% asfsd黄色fsdf 黄色  asd黄色fadsf 黄色  adasdf   2020299870@qq.com  asdfa % sdf     ";
        System.out.println(str.trim());

        System.out.println(str.startsWith("zs"));

        System.out.println(str.contains("黄色"));


        System.out.println(String.format("A喜欢 %d岁的姑娘",30));
        System.out.println(String.format("A喜欢 %s岁的姑娘","30"));
        System.out.println(String.format("%s@qq.com","2020299870"));
        System.out.println(String.format("余额:%f元",123.123459));
        System.out.println(String.format("余额:%.2f元",123.123459));


        String s1 = "abc";
        String s4 = "ABC";
        char[] c1 = {'a','b','c'};
        byte[] b1 = {65,66,67}; //A: 65

        String s2 = new String(c1);
        String s3 = new String(b1);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);


        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s3.hashCode());
        System.out.println(s4.hashCode());

    }

基本语法项目

家庭收支管理系统

家庭收支管理系统

Scanner + FileInputStream读取txt文件
        InputStream is = new FileInputStream("/Users/Shared/study/maven/springboot_quickstart/src/test/java/com/zs/尹成/字符串/test.txt");
        Scanner sc = new Scanner(is,"UTF8");//默认以UTF8编码读取文件
        long l = 0;
        sc.nextLine();
        while (sc.hasNext()){
            Manue manue = new Manue();
            String read = sc.nextLine();
            Scanner strsc = new Scanner(read);

            manue.id = strsc.nextInt();
            manue.name = strsc.next();
            manue.age = strsc.nextInt();

            if (manue.age >= 20 && manue.age <30){
                System.out.println( manue.id + "--" +  manue.name + "--" + manue.age);
            }
            l++;
        }
        class Manue{
		    int id;
		    String name;
		    int age;
		}

读取全部文本,正则搜索
    @Test
    public void test1() throws IOException {
        String alltext = new String(Files.readAllBytes(Paths.get("/Users/Shared/study/maven/springboot_quickstart/src/test/java/com/zs/尹成/字符串/test.txt")), "UTF8");
        String regex = "[1-9]\\d{4,13}\\s";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(alltext);
        while (m.find()){
            System.out.println(m.group().trim() + "@qq.com");
        }
    }
定时关机
    /**
     * 定时关机
     * shutdown -s -t 300
     * 取消关机:shutdown -a
     */
    @Test
    public void test05() throws InterruptedException{
        int i = 0;
        while (true){
            System.out.printf("当前是%d秒\n",i);
            Thread.sleep(1000);
            i++;
        }
    }

秒数转分钟
    /**
     * 输入秒数: 转 xx小时xx分钟xx秒
     */
    @Test
    public void test06(){
        String str1 = JOptionPane.showInputDialog("输入一个数");//输入
        int intdata = Integer.parseInt(str1);
        int hours,minutes,seconds;
        hours = intdata/3600;//小时
        seconds = intdata%60;//秒
        minutes = (intdata - hours*3600 - seconds)/60;
        str1 = "";
        str1 += hours + "小时" + minutes + "分钟" + seconds + "秒";
        JOptionPane.showMessageDialog(null,str1);
    }
十进制转十六进制
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个十进制的数");
        int num = input.nextInt();
//        int num = 1234;
        String hex = "";
        while (num != 0) {
            int data = num % 16;
            char nowchar = 0;
            if (data >= 0 && data <= 9){
                nowchar = (char) (data + '0');
            } else {
                nowchar = (char)(data - 10 + 'A');
            }
            hex = nowchar + hex;
            num/=16;
        }
        System.out.println(hex);
    }
打开win中程序

在这里插入图片描述
在这里插入图片描述

    /**
     * CMD 控制台
     */
    @Test
    public void test02(){
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            String cmdstr = bf.readLine();
            Process proc = Runtime.getRuntime().exec(cmdstr);
        } catch (IOException ioException) {

        }
    }
    /**
     * 关闭程序: taskill /f /im notepad.exe
     * 打开程序:notepad
     * @param args
     */
    public static void main(String[] args) {
        try {
            Process exec = Runtime.getRuntime().exec("calc");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
数字转中文格式(数字金额转大写)

窗体迷宫(AI:递归)
public class 迷宫 {

    @Test
    public void test1() {
        //创建数组窗体
        JFrame[][] jf = new JFrame[6][6];

        int[][] gamedata = new int[][]{
//                {0,  1,  2,  3,  4,  5},
//                {6,  7,  8,  9,  10, 11},
//                {12, 13, 14, 15, 16, 17},
//                {18, 19, 20, 21, 22, 23},
//                {24, 25, 26, 27, 28, 29},
//                {30, 31, 32, 33, 34, 35},

                {1, 0, 0, 2, 0, 0},
                {0, 2, 0, 0, 0, 2},
                {2, 0, 0, 2, 0, 0},
                {0, 0, 2, 0, 2, 0},
                {0, 2, 0, 0, 0, 0},
                {2, 0, 0, 0, 2, 0},
        };
        System.out.println(gamedata[0][1]);
        System.out.println(gamedata[1][0]);
        for (int i = 0; i < jf.length; i++) {
            for (int j = 0; j < jf[i].length; j++) {
                jf[i][j] = new JFrame("" + gamedata[i][j]);
//                jf[i][j] = new JFrame("" + i + "," + j);
                jf[i][j].setSize(100, 100);
                jf[i][j].setLocation(j * 100, i * 100);
                jf[i][j].setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                if (gamedata[i][j] == 0) {
                    jf[i][j].getContentPane().setBackground(Color.YELLOW);
                } else if (gamedata[i][j] == 1) {
                    jf[i][j].getContentPane().setBackground(Color.red);
                } else if (gamedata[i][j] == 2) {
                    jf[i][j].getContentPane().setBackground(Color.blue);
                } else {
                    jf[i][j].getContentPane().setBackground(Color.black);
                }


                jf[i][j].setVisible(true);
            }
        }

        int xpos = 0;
        int ypos = 0;
        while (true) {
            Object[] values = {"上", "下", "左", "右", "AI", "放弃"};
            Object value = JOptionPane.showInputDialog(null, "请选择", "输入", JOptionPane.INFORMATION_MESSAGE, null, values, values[0]);
            switch (value.toString()) {
                case "上":
                    if (xpos - 1 >= 0 && gamedata[xpos - 1][ypos] != 2) {
                        int temp = gamedata[xpos][ypos];
                        System.out.println(temp);
                        gamedata[xpos][ypos] = gamedata[xpos - 1][ypos];
                        System.out.println(gamedata[xpos][ypos]);
                        gamedata[xpos - 1][ypos] = temp;
                        System.out.println(gamedata[xpos - 1][ypos]);
                        xpos -= 1;
                        show(jf, gamedata);
                    }
                    break;
                case "下":
                    if (xpos + 1 <= 5 && gamedata[xpos + 1][ypos] != 2) {
                        int temp = gamedata[xpos][ypos];
                        gamedata[xpos][ypos] = gamedata[xpos + 1][ypos];
                        gamedata[xpos + 1][ypos] = temp;
                        xpos += 1;
                        show(jf, gamedata);
                    }
                    break;
                case "左":
                    if (ypos - 1 >= 0 && gamedata[xpos][ypos - 1] != 2) {
                        int temp = gamedata[xpos][ypos];
                        gamedata[xpos][ypos] = gamedata[xpos][ypos - 1];
                        gamedata[xpos][ypos - 1] = temp;
                        ypos -= 1;
                        show(jf, gamedata);
                    }
                    break;
                case "右":
                    if (ypos + 1 <= 5 && gamedata[xpos][ypos + 1] != 2) {
                        int temp = gamedata[xpos][ypos];
                        gamedata[xpos][ypos] = gamedata[xpos][ypos + 1];
                        gamedata[xpos][ypos + 1] = temp;
                        ypos += 1;
                        show(jf, gamedata);
                    }
                    break;
                case "AI":
                    findway(gamedata,0,0);
                    show(jf, gamedata);
                    break;
                default:
                    System.exit(0);
            }
            System.out.println(value);
        }
    }

    public void show(JFrame[][] jf, int[][] gdata) { //显示数据在窗体
        for (int i = 0; i < jf.length; i++) {
            for (int j = 0; j < jf[i].length; j++) {
                jf[i][j].setTitle("" + gdata[i][j]);

                if (gdata[i][j] == 0) {
                    jf[i][j].getContentPane().setBackground(Color.YELLOW);
                } else if (gdata[i][j] == 1) {
                    jf[i][j].getContentPane().setBackground(Color.red);
                } else if (gdata[i][j] == 2) {
                    jf[i][j].getContentPane().setBackground(Color.blue);
                } else {
                    jf[i][j].getContentPane().setBackground(Color.black);
                }
            }
        }
    }

    static boolean canout = false;

    public boolean findway(int[][] gdata, int i, int j) {
        gdata[i][j] = 3;
        if (i == 5 && j == 5) {
            canout = true;
            return true;
        } else {
            //向上
            if (i - 1 >= 0 && gdata[i - 1][j] < 2 && canout == false) {
                findway(gdata, i - 1, j);//步行到 i - 1
            }
            //向下
            if (i + 1 <= 5 && gdata[i + 1][j] < 2 && canout == false) {
                findway(gdata, i + 1, j);//步行到 i - 1
            }
            //向左
            if (j - 1 >= 0 && gdata[i][j - 1] < 2 && canout == false) {
                findway(gdata, i, j - 1);//步行到 i - 1
            }
            //向右
            if (j + 1 <= 5 && gdata[i][j + 1] < 2 && canout == false) {
                findway(gdata, i, j + 1);//步行到 i - 1
            }


            if (canout != true) {
                gdata[i][j] = 1;//走不出回到原点
            }
        }
        return canout;
    }


}

面试题

自增运算符

 public static void main(String[] args) {
     int i = 1;
     i = i++;
     int j = i++;
     int k = i + ++i*i++;
     System.out.println("i=" + i);
     System.out.println("j=" + j);
     System.out.println("k=" + k);
 }
i=4
j=1
k=11

分析过程

int i = 1;//定义变量
i = i++;//易得 i = 1
int j = i++;//易得 i = 2,j = 1;

int k = i + ++i*i++;
/*
1.压栈操作时从左向右,i 的值入栈
i = 2 		栈 2

2. ++i 先自增,后入栈
i = 3		栈 2 3

3. i++ 先入栈,后自增
i = 3		栈 2 3 3
i = 4		栈 2 3 3

4.做运算 先乘
3*3 = 9 
i = 4		栈 2 9

5.做运算 加操作
2 + 9
i = 4		栈 11

6. 赋值操作
将操作数栈的值赋给 k 变量
i = 4		栈 
k = 11
j = 1
*/ 

嵌套循环

100 以内所有的质数

质数:只能被1 和 他本身整除的自然数

判断思路:n 是否是质数, 循环[2,n-1]能否整除n
最小的质数是 2

 //最小的质数是2,循环从2开始[2,100]
 boolean flag = true;
 int count = 0;
 for (int i = 2; i <= 100; i++) {
     //n 是否是质数 在[2,n-1]中找是否有可以将n除尽的数,如果有则 n 不是质数
     for (int j = 2; j <= i-1; j++) {
         if (i%j == 0){
             //被除尽说明不是质数
             flag = false;
             break;
         }
     }
     if (flag){
         count++;
         System.out.println(i);
     }
     flag = true;
 }
 System.out.println("质数的个数是:" + count);
        //1000000 以内所有的质数
        boolean flag = true;
        int count = 0;
        long start = System.currentTimeMillis();
        for (int i = 2; i <= 1000000; i++) {
            for (int j = 2; j <= i-1; j++) {
                if (i%j == 0){
                    //被除尽说明不是质数
                    flag = false;
                    break;
                }
            }
            if (flag){
                count++;
                //System.out.println(i);
            }
            flag = true;
        }
        System.out.println("质数的个数是:" + count);
        long end = System.currentTimeMillis();
        System.out.println("用时:" + (end - start));
    }
    
质数的个数是:78498
用时:111114


	//最小的质数是2,循环从2开始[2,100]
	boolean flag = true;
	int count = 0;
	long start = System.currentTimeMillis();
	for (int i = 2; i <= 1000000; i++) {
	    //n 是否是质数 在[2,n-1]中找是否有可以将n除尽的数,如果有则 n 不是质数
	    //n 是否是质数 在[2,n/2向下取整] n/([n/2向上取整,n-1)中的任何一个数结果都在(1,2)之间不可能被整除,所以不用判断
	    //n 是否是质数 在[2,√n] 一个数开根号为分界点,根号左边如果有可以除尽的数根号(√n,n/2)右边一定有一个整数和他对应,如果根号前找不到,那么在根号右边得到的一定也是无法整除的
	    for (int j = 2; j <= Math.sqrt(i); j++) {
	        if (i%j == 0){
	            //被除尽说明不是质数
	            flag = false;
	            break;
	        }
	    }
	    if (flag){
	        count++;
	        //System.out.println(i);
	    }
	    flag = true;
	}
	System.out.println("质数的个数是:" + count);
	long end = System.currentTimeMillis();
	System.out.println("用时:" + (end - start));

质数的个数是:78498
用时:296



	//最小的质数是2,循环从2开始[2,100]
	int count = 0;
	long start = System.currentTimeMillis();
	label:for (int i = 2; i <= 1000000; i++) {
	    for (int j = 2; j <= Math.sqrt(i); j++) {
	        if (i%j == 0){
	            continue label;
	        }
	    }
	    count++;
	}
	System.out.println("质数的个数是:" + count);
	long end = System.currentTimeMillis();
	System.out.println("用时:" + (end - start));

质数的个数是:78498
用时:281
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠闲的线程池

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值