2-1 关键字与保留字
1.关键字:
被java语言赋予了特殊含义,用作专门用途的字符串
特点:关键字中所有字母都为小写
2.JAVA保留字:现有java版本尚未使用,但以后版本可能会作为关键字使用。自己命名标识符时要避免使用这些保留字
goto/const
2-2 标识符(Identifier)
1.标识符
Java对各种变量、方法和类等要素命名时使用的字符序列成为标识符(可以自己起名字的地方)
2.标识符的命名规则:
1)由26给英文字母大小写,0-9,_或$组成
2)数字不可以开头
3)不可以使用关键字和保留字,但可以包含关键字和保留字
4)java中严格区分大小写,长度无限制。
5)标识符不能包含空格
如果不遵守以上的规则,编译不通过
3.标识符的命名规范:
1)包名:多单词组成时所有字母都小写:xxxyyyzzz
2)类名、接口名:多单词组成时,所有单词的首字母大写:XxxYyyZzz
3)变量名、方法名:多单词组成时,第一个单词首字母小写,第二个单词首字母大写:xxxYyyZzz
4)常量名:所有字母都大写。多单词时每个单词用下划线连接:XXX_YYY_ZZZ
(若不遵守如下的规范,编译可以通过!建议大家遵守)
2-3 变量
1.概念:
作用:在内存中保存数据
注意:
1)Java中每个变量必须先声明,后使用
2)使用变量名来访问这块区域的数据
3)变量的作用域:其定义所在的一对{}内
4)变量只有在其作用域内才有效
5)同一个作用域内,不能定义重名的变量
2.变量的类型:
1)按数据类型分
2)变量在类中声明的位置
成员变量 vs 局部变量
整数类型:
byte/short/int/long
注意:声明long型变量必须以 'L' 或者 'l'结尾
通常定义变量为int 型
class VariableTest { public static void main(String[] args) { long b1 = 128L;//变量的定义 System.out.println(b1);//变量的使用 } }
浮点型:
float/double
注意:定义float类型变量时,变量值的末尾要以 'f' 或 'F' 结尾
定义浮点型变量时,通常用double
字符型:
char (1字符=2字节)
变量的使用:
class VariableTest { public static void main(String[] args) { char b1 = 'a';//变量的定义 System.out.println(b1);//变量的使用 if(b1.equals(""))//比较字符型是否一样。返回布尔型变量 { } } }
表示方式:
1.声明一个字符 2.转义字符 3.直接使用Unicode值来表示字符常量
2)
//转义字符的使用 class VariableTest { public static void main(String[] args) { char c5 = '\n';//变量的定义 System.out.print("Hello" + c5);//变量的使用 System.out.println("World"); } }
想单独输出\n ’‘”“ \方法,在这些转义字符前加\
3)直接使用Unicode值来表示字符常量
class VariableTest { public static void main(String[] args) { char c6 = '\u0123';//变量的定义 System.out.print(c6);//变量的使用 }//输出结果为'?' }
关于UTF-8
布尔型(boolean):
1)只能取两个值之一:(true/false)
2)常常在条件判断、循环结构中使用
class VariableTest { public static void main(String[] args) { boolean isMarried = true;//变量的定义 if(isMarried) { System.out.println("你不能参加单身party了,很遗憾!"); } else { System.out.println("你可以多耍朋友"); } } }
3.自动类型转换
讨论7中基本数据类型变量间的运算。不包含boolean类型
1)自动类型提升
当容量小的数据类型变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型
此时的容量大小指的时表示数的范围的大和小
byte 、char、short (此三种变量间运算(包括同类型变量运算),均自动转换为int型变量)--> int --> long --> float --> double
{ public static void main(String[] args) { byte b1 = 2; int i1 = 129; //byte b2 = b1 + i1; //编译不通过 int b2 = b1 + i1; System.out.println(b2); float f = b1 + i1; System.out.println(f);//131.0 short s1 = 123; double d1 = s1; System.out.println(d1);//123.0 char s2 = 'a'; int s3 = 4; int s4 = s2 + s3; System.out.println(s4);//101 short s5 = 4; int s6 = s2 + s5; System.out.println(s6); short s7 = 4; int s8 = s7 + s2; System.out.println(s8); } }
4.强制类型转换:(自动类型提升运算的逆运算)
1)需要使用强转符
2)做截断操作,截断后可能损失精度
class VariableTest3 { public static void main(String[] args) { double d1 = 12.3; int i1 = (int)d1; System.out.println(i1); int i2 = 128; byte b = (byte)i2; System.out.println(b);//输出结果为-128(把第一位的1截去,剩下的全都为0,故补码为最小数-128) } }
补充:
1)编码情况 定义long型变量,部分情况下后面没加'l'也能正常运行:
未加后缀'l'时,long型变量作为int 型变量使用,将int型值赋给long型变量,相当于做了一次自动类型提升
2)对于整形常量,默认为int型
整形常量与变量做运算时,默认为变量与int型常量做运算
class VariableTest4 { public static void main(String[] args) { long l = 12345; System.out.println(l);//正常输出 /* long l = 12345562159626; System.out.println(l);//过大的整数,编译失败 */ long l1 = 1324564615615l; System.out.println(l1);//正常输出 /*float f1 = 12.3; System.out.println(f1);编译失败 */ byte b = 12; //byte b1 = b + 1;编译失败 //float f1 = b + 12.3;//编译失败 } }
字符串类型String:
1)string 里面可以不放字符,不超内存即可;
char 型有且只能放一个字符
2)string可以和8种基本数据变量做运算,且运算只能是连接运算'+'
3)输出类型是String类型
if(b1.equals("asbs"))//比较字符型是否一样。返回布尔型变量
{
}
2-3 变量之进制
整数的表示方式
2-4 运算符
1.算术运算符:
class ArithmeticTest { public static void main(String[] args) { //除号:/ int num1 = 12; int num2 = 5; int res1 = num1 / num2; System.out.println(res1);//2 int res2 = num1 / num2 * num2;//10 System.out.println(res2); double res3 = num1 / num2; System.out.println(res3);//2.0(int型运算完再自动转换为double) double res4 = (double)num1 / num2; System.out.println(res4);//2.4(double与int运算,自动提升为double) //取余运算: //结果符号与被模数符号相同 //开发中,通常用取模运算来判断是否能被除尽的情况 int m1 = 12; int n1 = 5; System.out.println("m1 % n1 = " + m1 % n1);//2 int m2 = -12; int n2 = 5; System.out.println("m2 % n2 = " + m2 % n2);//-2 int m3 = 12; int n3 = -5; System.out.println("m3 % n3 = " + m3 % n3);//2 int m4 = -12; int n4 = -5; System.out.println("m4 % n4 = " + m4 % n4);//-2 //++(front)先自增1,再运算 //(behind)++先运算,再自增1 int a1 = 10; int b1 = ++a1; System.out.println(b1);//11 int a2 = 10; int b2 = a2++; System.out.println(b2);//10(先将a2的值赋给b2,a2再++) short s1 = 10; s1++;//s1 = s1 + 1;编译不通过,需改为s1 = (short)(s1 + 1); System.out.println(s1);//自增1不会改变变量的类型 byte b11 = 127; b11++; System.out.println("b1 = " + b11); } }
2.赋值运算符
=
拓展+=、-=、*=、/=、%=(使用此赋值方法,变量不改变本身的类型(利用自动类型转换或强制类型转换))
注意:1)当赋值符号两侧变量类型不同时,采用自动类型转换或强制类型转换进行处理
2)支持连续赋值
class SetValueTest { public static void main(String[] args) { //赋值符号:= int i1 = 10; int j1 = 10; System.out.print("i1 = " + i1); System.out.println(" j1 = " + j1); //等价于 int i2, j2; i2 = j2 = 10; System.out.print("i2 = " + i2); System.out.println(" j2 = " + j2); int num1 = 10; num1 += 2; System.out.println(num1); byte b1 = 10;//与b1 = b1 + 2;有别 b1 += 2; System.out.println(b1);//编译通过,输出12(不会改变本身的类型) //开发中,如果希望变量实现+2的操作,有几种方法?(前提:int num = 10;) //num = num + 2; //num += 2;(推荐) //text1 int i3 = 1; i3 *= 0.1; System.out.println(i3);//0 i3++; System.out.println(i3);//1 //text4 int n = 10; n += (n++) + (++n); System.out.println(n);//32 } }
3.比较运算符
注:1)比较运算符的结果都是boolean型;
2)==不能写成=
class CompareText { public static void main(String[] args) { int i = 10; int j = 20; System.out.println(i == j);//false System.out.println(i = j);//20 } }
4.逻辑运算符
1)逻辑运算符的类型
逻辑运算符只适用于boolean类型的变量
2)逻辑运算规则
异或:不同为true,相同为false
3)逻辑与 与 运算与(&&只要有一个错,后面的不用看)
a.两者运算结果相同
b.当符号左边为true时,继续执行符号右面的运算
c.当符号左边为false时,&继续执行符号右面的运算,&&不执行符号右面的运算
4)逻辑或 与 运算或(||只要有一个对,后面的不用看)
a.两者运算结果相同
b.当符号左边为false时,继续执行符号右面的运算
c.当符号左边为true时,&继续执行符号右面的运算,&&不执行符号右面的运算
开发中,推荐使用短路
class LogicTest { public static void main(String[] args) { //区分&与&& boolean b1 = true; int num1 = 10; if((num1++>0) & (num1++<0) &(num1++>0)) { System.out.println("1"); } else { System.out.println("2"); } System.out.println("num1 = " + num1);//13 boolean b2 = true; int num2 = 10; if((num2++>0) && (num2++<0) &&(num2++>0)) { System.out.println("1"); } else { System.out.println("2"); } System.out.println("num2 = " + num2);//12 //区分:|与|| boolean b3 = true; int num3 = 10; if(b3 | (num3++) > 0) { System.out.println("1"); } else { System.out.println("2"); } System.out.println("num3 = " + num3);//11 boolean b4 = true; int num4 = 10; if(b4 || (num4++) > 0) { System.out.println("1"); } else { System.out.println("2"); } System.out.println("num4 = " + num4);//10 } }
5.位运算符
操作的都是整形的数据
1)左移运算:二进制码整体向左移n位。 左移n位:原数乘2的n次方
注意:左移有范围,超出范围,左移不规范
2)右移运算:二进制码整体向右移n位。 右移n位:原数除2的n次方
3) 异或运算:(m^n)^n = m;
(左移右移对负数均成立)
class BitTest { public static void main(String[] args) { int i = 21; System.out.println("i << 2:" + (i << 3)); int m = 12; int n = 5; System.out.println("m & n = " + (m & n)); System.out.println("m | n = " + (m | n)); System.out.println("m ^ n = " + (m ^ n)); //练习:交换两个变量的值 int num1 = 10; int num2 = 20; /*方式一:定义临时变量 int temp = num1; num1 = num2; num2 = temp; System.out.println("num1 = " + num1 + ",num2 = " + num2);*/ /*方式二: num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; System.out.println("num1 = " + num1 + ",num2 = " + num2);*/ //方式三:使用位运算符 num1 = num1 ^ num2; num2 = num1 ^ num2; num1 = num1 ^ num2; System.out.println("num1 = " + num1 + ",num2 = " + num2); } }
6.三元运算符
注意:表达式1与表达式2可以统一为同种类型,且用统一的类型接受
凡是可以使用三元运算符的地方,都可以改写为if-else, 反之,不成立;
如果既可以使用三元运算符,又可以使用if-else,使用三元运算符
class ThreeElement { public static void main(String[] args) { //获取两个整数的较大值: int m = 12; int n = 5; int l = 7; int max = (m > n) ? m : n; //System.out.println(max); max = (m > n) ? ((m > l) ? m : l) : ((n > l) ? n : l);//比较三个数的最大值 System.out.println(max); } }
7.运算符的优先级
通法:加括号
*、键盘输入
如何从键盘获取不同类型的变量:需要使用Scanner类
具体实现步骤:
1.导包:import java.util.Scanner;
2.Scanner的实例化:Scanner scan = new Scanner(System.in);
3.调用Scanner类的相关方法,来获取指定类型的变量
注意:对于char型的获取,Scanner没有提供相关的方法,只能获取一个字符串;
方法charAt():获取String型变量中某个位置的字符。例:获取gender中定义的第一个字符:
Scanner scan = new Scanner(System.in);
String gender = scan.next();
char genderChar = gender.charAt(0);
须要根据对应的方法来输入指定类型的值。如果输入的数据类型与要求的类型不匹配时,会报异常:InputMismatchException,导致程序终止
/* 如何从键盘获取不同类型的变量:需要使用Scanner类 具体实现步骤: 1.导包:import java.util.Scanner; 2.Scanner的实例化:Scanner scan = new Scanner(System.in); 3.调用Scanner类的相关方法,来获取指定类型的变量 */ import java.util.Scanner; class ScannerTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("请输入你的姓名:"); String name = scan.next(); System.out.println(name); System.out.println("请输入你的年龄:"); int num = scan.nextInt(); System.out.println(num); System.out.println("请输入你的体重:"); double weight = scan.nextDouble(); System.out.println(weight); System.out.println("你是否单身"); boolean b1 = scan.nextBoolean(); System.out.println(b1); //对于char型的获取 System.out.println("请输入你的性别:(男/女)"); String gender = scan.next(); char genderChar = gender.charAt(0); System.out.println(genderChar);//获取索引为0位置上的字符 } }
2-5 程序流程控制
三种流程控制结构:
顺序结构
分支结构
循环结构
*获取随机数
Math中的random方法,随机产生[0.0 , 1.0)的数
要产生[x , y)
double value = Math.random() * (y - x + 1) + x;
再对random进行强转
*.计算时间
获取当前时间距离1970-01-01 00:00的毫秒数
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
double timeInterval = (double)(start - end)/1000;
1.分支结构
1).if-else语句
import java.util.Scanner; class IfTest3 { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); System.out.println("please input dog's age:"); double ageDog = scanf_s.nextInt(); double ageHuman; if(ageDog >= 0 && ageDog <= 2) { ageHuman = ageDog * 10.5; System.out.println(ageHuman); } else if (ageDog > 2) { ageHuman = (ageDog - 2) * 4 + 10.5 * 2; System.out.println(ageHuman); } else { System.out.println("Input Error!"); } } }
import java.util.Scanner; class IfTest4 { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); int value1 = (int) (Math.random() * 90 + 10); System.out.println("请输入两位数:"); int num1 = scanf_s.nextInt(); int num2, num3, value2, value3; num2 = num1 / 10; num3 = num1 %10; value2 = value1 /10; value3 = value1 %10; if (num1 == value1) { System.out.println("Congratulation! you get 10,000$"); } else if (num2 == value2 && num3 == value3) { System.out.println("Congratulation! you get 3,000$"); } else if(num2 == value2 || num3 == value3) { System.out.println("Congratulation! you get 1,000$"); } else if(num2 == value3 || num3 == value2) { System.out.println("Congratulation! you get 500$"); } else { System.out.println("Sorry, you did't win the prize"); } } }
import java.util.Scanner; class IfExer3 { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); System.out.println("please input your height:"); int height = scanf_s.nextInt(); System.out.println("please input your wealth:"); int wealth = scanf_s.nextInt(); System.out.println("What do you think of your look:(帅/丑)"); String look = scanf_s.next(); boolean b1, b2, b3; b1 = height >= 180; b2 = wealth >= 10000000; b3 = look.equals("帅"); if (b1 && b2 && b3) { System.out.println("我一定要嫁给他!!!"); } else if(b1 || b2 || b3) { System.out.println("行吧,比上不足,比下有余。"); } else { System.out.println("我不嫁!"); } } }
2)switch-case语句
说明:
1.根据switch表达式中的值,依次匹配各个case中的常量。一旦匹配成功,则进入相应case结构中,调用其执行语句。当调用完执行语句以后,则仍然继续向下执行其他case结构中的执行语句,知道遇到break关键字或此switch-case结构末尾结束为止
2.break,可以使用在switch-case结构中,表示一旦执行到此关键字,就跳出switch-case结构
3.switch结构中的表达式,只能是如下的6中数据类型之一:byte、short、char、int、枚举类型()、String类型
class SwitchCaseTest { public static void main(String[] args) { int num = 2; switch(num) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; case 3: System.out.println("three"); break; default: System.out.println("four"); break; } } }
/* 输入年月日,求改日是本年第几天 */ import java.util.Scanner; class SwitchExer1 { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); System.out.println("请输入年份:"); int year = scanf_s.nextInt(); System.out.println("请输入月份:"); int month = scanf_s.nextInt(); System.out.println("请输入日期:"); int day = scanf_s.nextInt(); int sumDay = 0; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { switch(month) { case 12: sumDay += 31; case 11: sumDay += 30; case 10: sumDay += 31; case 9: sumDay += 30; case 8: sumDay += 31; case 7: sumDay += 31; case 6: sumDay += 30; case 5: sumDay += 31; case 4: sumDay += 30; case 3: sumDay += 31; case 2: sumDay += 29; case 1: sumDay += 31; } } else { switch(month) { case 12: sumDay += 31; case 11: sumDay += 30; case 10: sumDay += 31; case 9: sumDay += 30; case 8: sumDay += 31; case 7: sumDay += 31; case 6: sumDay += 30; case 5: sumDay += 31; case 4: sumDay += 30; case 3: sumDay += 31; case 2: sumDay += 28; case 1: sumDay += 31; } } System.out.println(year + "年" + month + "月" + day + "日" + "是" + year + "年的第" + sumDay + "天" ); } }
说明:
1.switch-case能转化为if-else,反之不成立
2.既可以使用switch-case(表达式)又可以使用取值情况不太多,优先用switch-case
2.循环结构
1)for循环
/* 做一个程序,实现输入两个数,输出这两个数的最大公约数和最小公倍数 */ import java.util.Scanner; class ForTest { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); System.out.println("please input two numbers one by one:"); int num1 = scanf_s.nextInt(); int num2 = scanf_s.nextInt(); int i, maxCommonDivisor, minCommonMultiple; if (num1 > num2)//给两数排序 { int temp; temp = num1; num1 = num2; num2 = temp; } for (i = num1; i > 0 ;i-- ) { if (num1 % i == 0 && num2 % i == 0) { maxCommonDivisor = i; System.out.println("The greatest common divisor is " + maxCommonDivisor); break; } //find the maxCommonDivisor } for (i = num2 ;;i++ ) { if (i % num2 == 0 && i % num1 == 0 ) { minCommonMultiple = i; System.out.println("The smallest common multiple is " + minCommonMultiple); break; } //find the minCommonMultiple } } }
2)while循环
while与for的区别:初始化条件的作用范围不同
3)do-while循环
*.嵌套循环
方法:System.currentTimeMillis//计算代码运行时间
嵌套打印:
第一层(i):打印的行数n;
第二层(j):元素个数用与i有关的表达式控制,
for( j = 1; j <= i有关的表达式 ; j++ )
{
输入内容用此处表达式表示;
}
import java.util.Scanner; class NestedLoop { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); int i, j, k, x, num; //输出4行6列* for (i = 0; i < 4 ;i++) { for (j = 0; j < 6 ;j++) { System.out.print('*'); } System.out.print('\n'); } //输出5行*金字塔 for (i = 1; i <= 5 ;i++) { for (j = 0; j < i ;j++) { System.out.print('*'); } System.out.println(); } //输出数字金字塔 System.out.println("please input the number you consider:"); num = scanf_s.nextInt(); for (i = 1; i <= num ;i++) { for (j = num - i; j > 0 ;j--) { System.out.print(' '); } for (k = 1; k <= 2 * i - 1 ;k++) { System.out.print(i); } System.out.println(); } } }
打印杨辉三角
/* 输出杨辉三角 */ import java.util.Scanner; class YanghuiTriangle { public static void main(String[] args) { Scanner scanf_s = new Scanner(System.in); int i, j, k, x, num; System.out.println("please input the row of the triangle:"); num = scanf_s.nextInt(); int num1, num2, num3, pro1, pro2, pro3; for (i = 1; i <= num ;i++) { for (j = num - i; j > 0 ;j--)//print "space" { System.out.print(' '); } num1 = i - 1;//(n - 1)! pro1 = 1; for (; num1 > 0 ;num1--) { pro1 *= num1; } for (k = 1; k <= (2 * i - 1) ;k++) { if (k == 1)//When k == 1,computer can't identify C(n, 0). So we need to input 1 by hand. { System.out.print("1"); } else//To calculate C(n - 1,m - 1). n is the row number,m is the place where the number is in this row. { if (k % 2 != 0) { pro2 = 1; pro3 = 1; num2 = (k - 1) / 2;//(k + 1) / 2 - 1; num3 = i - ((k + 1) / 2); for (; num2 > 0 ;num2--)//(m - 1)! { pro2 *= num2; } for (; num3 > 0 ;num3--)//(n - m)! { pro3 *= num3; } System.out.print(pro1 / pro2 /pro3); } else { System.out.print(' '); } } } System.out.println(); } } }
打印质数(算法的优化)
class PrimeNumberTest2 { public static void main(String[] args) { int i, j; boolean isFlag = true; int count = 0; long start = System.currentTimeMillis();//获取当前时间距离1970-01-01 00:00的毫秒数 for (i = 2; i <= 100000 ;i++) { for (j = 2; j <= Math.sqrt(i) ;j++)//优化2 0.294s { if (i % j == 0) { isFlag = false; break;//优化算法1 } } if (isFlag == true) { //System.out.println(i); count++;//无输出时间为0.007s } isFlag = true; } long end = System.currentTimeMillis();//获取当前时间距离1970-01-01 00:00的毫秒数 System.out.println("程序运行的时间为" + (double)(end - start) / 1000 + "s");//计算程序运行的时间,以判断程序运行的效率 //有break运行时间为1.042s,无break运行时间为7.759s } }
实现方式2:
/* 一百以内所有素数的输出: */ class PrimeNumberTest { public static void main(String[] args) { int i, j; label: for (i = 2; i <= 100 ;i++) { for (j = 2; j <= Math.sqrt(i) ;j++) { if (i % j == 0) { continue label; } } System.out.println(i); } } }
*.特殊关键字的使用:break,continue
1.使用范围:
break: switch-case 相同点:关键字后面不能声明执行语句
循环结构中 结束当前循环
continue: 循环结构中 结束当次循环
class BreakContinueTest { public static void main(String[] args) { int i; for (i = 1; i <= 10 ;i++) { if (i % 4 ==0) { //break;//123 continue;//123567910 } System.out.println(i); } } }
break,continue默认跳出包裹此关键字最近的一层循环
若想跳出指定循环:在指定循环前加标签,在break后面写标签名;