第二章----基本语法
第二章:基本语法
- 1、关键字和保留字
- 2、标识符
- 2.1、标识符的使用
- 2.2、标识符的命名规则
- 2.3、标识符的命名规范
- 3、变量
- 3.1、变量分类
- 3.2、整数类型:byte、short、int、long
- 3.3、浮点类型:float、double
- 3.4、字符类型:char
- 3.5、布尔类型:boolean
- 3.6、基本数据类型转换
- 3.6.1、自动类型提升
- 3.6.2、强制类型转换
- 3.7、java 新特性:数据分隔
- 4、运算符
- 4.1、算数运算符
- 4.2、 赋值运算符
- 4.3、比较运算符
- 4.4、逻辑运算符
- 4.5、位运算符
- 4.6、三元运算符
- 5、流程控制
- 5.1、分支结构
- 5.1.1、if-else
- 5.1.2、switch-case
- 5.2、循环结构
- 5.2.1、for、while、do-while
- 5.2.2、无限循环
- 5.2.3、嵌套循环
- 5.2.4、break和continue和return的使用
- 附录
- 键盘录入
- Scanner
- BufferedReader
- 随机数
- 字符串
- split
- String的值传递机制
- length()、indexOf()
- charAt()、subString()
- lastIndexOf()、toUpperCase()、toLowerCase()
- trim()、startsWith()、contains()、format()、hashCode()
- 基本语法项目
- 家庭收支管理系统
- Scanner + FileInputStream读取txt文件
- 读取全部文本,正则搜索
- 定时关机
- 秒数转分钟
- 十进制转十六进制
- 打开win中程序
- 数字转中文格式(数字金额转大写)
- 窗体迷宫(AI:递归)
- 面试题
- 自增运算符
- 嵌套循环
- 100 以内所有的质数
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型变量,通常使用一对’’,内部只能写一个字符
- 表示方式:
- 声明一个字符
- 转义字符
- 直接使用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 = 5int result1 = num1/num2;//2
double result2 = num1/num2;//2.0double 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 //-2100 % 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=11int 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++;//-128int 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 << 2712 & 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=81for (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的使用
break | switch-case、循环结构 |
continue | 循环结构中 |
return | 结束一个方法 |
附录
键盘录入
Scanner
Scanner sc = new Scanner(System.in);
//int
int num = sc.nextInt();
//string
next();
nextLine();
//double
nextDouble()
//boolean
nextBoolean();
BufferedReader
/*** CMD 控制台*/@Testpublic void test02(){try {BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));String cmdstr = bf.readLine();Process proc = Runtime.getRuntime().exec(cmdstr);} catch (IOException ioException) {}}
随机数
@Testpublic 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
@Testpublic 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* ==* 值传递机制*/@Testpublic void test1(){String str1 = "calc"; //常量池中,返回常量池中地址引用String str2 = str1; //浅拷贝String str3 = new String("calc"); //堆区,动态分配,自动回收,System.gcString 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);//地址相同 trueSystem.out.println(str2 == str3);//地址不同 falseSystem.out.println(str3 == str4);//地址不同 falseSystem.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()**/@Testpublic void test2(){String str = "azsfadfzssdfafasdfa zs adfadsfzsasdfafzs";int ch = str.length(); // 字符串长度int pos1 = str.indexOf("zs");//第一次出现的位置int pos2 = str.indexOf("123"); //-1int 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*/@Testpublic 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*/@Testpublic 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 : 字符串的唯一标识* */@Testpublic 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: 65String 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;}
读取全部文本,正则搜索
@Testpublic 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*/@Testpublic void test05() throws InterruptedException{int i = 0;while (true){System.out.printf("当前是%d秒\n",i);Thread.sleep(1000);i++;}}
秒数转分钟
/*** 输入秒数: 转 xx小时xx分钟xx秒*/@Testpublic 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 控制台*/@Testpublic 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 迷宫 {@Testpublic 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 栈 22. ++i 先自增,后入栈
i = 3 栈 2 33. i++ 先入栈,后自增
i = 3 栈 2 3 3
i = 4 栈 2 3 34.做运算 先乘
3*3 = 9
i = 4 栈 2 95.做运算 加操作
2 + 9
i = 4 栈 116. 赋值操作
将操作数栈的值赋给 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
第二章----基本语法相关推荐
- 【JAVA SE】第二章 Java语法基础、数据类型、基本类型的字面值、基本类型的类型转换和运算规则
第二章 Java语法基础.数据类型.基本类型的字面值.基本类型的类型转换.运算规则和标识符命名风格 文章目录 第二章 Java语法基础.数据类型.基本类型的字面值.基本类型的类型转换.运算规则和标识符 ...
- LLVM 极简教程: 第二章 实现语法分析器和AST
第二章 实现语法分析器和AST 原文: Implementing a Parser and AST 本章简介 欢迎进入"用LLVM开发新语言"教程的第二章.在本章中,我们将以第一章 ...
- JSP实用教程第二章-JSP语法
目录 前言 2.1 JSP页面的基本结构 2.2声明变量和定义方法 2.2.1 声明变量 2.22 定义方法和类 2.3Java程序片 2.4Java表达式 2.5 JSP中的注释 2.6 JSP指令 ...
- JSP实用教程——第二章JSP语法
目录 2.1 JSP页面的基本结构 2.2 声明变量和定义方法 2.2.1 声明变量 2.2.2 定义方法和类 2.3 Java程序片 2.4 Java表达式 2.5 JSP指令标记 2.5.1 pa ...
- 《C语言陷阱与缺陷》第二章【语法陷阱】上
目录 ✊ 一.理解函数声明 ☝️ 二.运算符的优先级问题 ✌️ 三.注意作为语句结束标志的分号 ✊ 一.理解函数声明 先来看下面这条语句: (* (void(*) () ) 0 ) (); 这样的表达 ...
- 编译原理语法分析_斯坦福大学《编译原理》学习记录 - 第二章:语法分析器
05-01: Introduction to Parsing 语法分析 parser的作用: 05-02: Context Free Grammars 上下文无关文法 CFG(上下文无关文法)回答了一 ...
- JSP实用教程——第二章:JSP语法
JSP基本语法 在传统的HTML页面文件中嵌入脚本语言和JSP标签就构成了一个JSP页面文件.一个JSP页面可有5中元素组合而成. HTML页面内容 JSP注释 JSP指令 JSP脚本元素 JSP动作 ...
- 第二章 疯狂Caché 语法规则
文章目录 第二章 Caché 语法规则 区分大小写 标识符 Unicode 空格 注释 例程和方法的int代码中的注释 例程和方法的MAC代码中的注释 方法代码之外的类定义中的注释 文字值 字符串文字 ...
- 使用java实现面向对象编程第二章_java面向对象编程——第二章 java基础语法
第二章 java基础语法 1.java关键字 abstract boolean break byte case catch char class const continue default do d ...
最新文章
- 自动驾驶第一案结果敲定,谷歌无人驾驶和Uber达成2.5亿美元和解协议
- 分布式:阿里云HSF转dubbo+zookeeper
- 读书笔记007:《伤寒论》- 手少阴心经
- linux ipset 流量,linux中ipset命令的使用方法详解
- [jQuery] 通过ajax保存到服务器,成功显示信息.
- 如何取消提交我在Git中的最后一次提交[重复]
- SAP结转方法:表结法、帐结法
- ECshop商城开发系列视频教程后盾网VIP课程
- 根据指定时间范围取得对应(第几)周信息,以及一年当中所有周时间范围列表信息(可用于学期第几周,年第几周)
- Python模块之Pandas模块学习笔记
- 基于HC-05蓝牙模块的STM32无线控制智能系统硬件开发
- Unity 日志输出
- java.lang.NoSuchFieldError: count at org.eclipse.jface.viewers.ColumnViewer$1.mouseDown
- 互联网快讯:猿辅导凭优质教学获好评;粉笔科技积极布局打造双核驱动;科创板上市公司突破400家
- 从android恢复到iphone,iPhone换到安卓机有多难适应?看看是怎么恢复过来的!
- fedora14配置无线连接
- 首届“兴智杯”产业赛收官,文心大模型助推产业创新
- NOJ-1401 乘车费用 题解要点
- 百度sitemap Api自动提交收录方法
- CQUPT 2023毕业论文中的Mathtype公式编号及其图表的题注
热门文章
- 基于用户的协同过滤来构建推荐系统(附代码)
- 【经验分享】在研究中,你是否踩过这些工程的“坑”?
- 测试需求分析第二部分
- 阿里粗排技术体系与最新进展
- 手机屏坏了怎么把里面存东西取出来_三年来,这十八个有关MT4的问题被问了三千遍...
- delphi idtcpclient 发送十六进制00_91413足球推荐分析 法甲 04:00 南特 VS 巴黎圣日尔曼...
- Star Schema完全参考手册读书笔记一
- CCF	201812-2小明放学
- 函数的基本知识,定义,调用,参数,返回值,说明文档,函数的嵌套及应用
- throw与throws