Java学习笔记
1、常见数据类型
//int、long后加L、short、char、byte、float后加F、double、boolean
2、面试题:进制的书写
/* 二进制0b 十进制 八进制0 十六进制0x 当前缀不同时,所代表的值也不同 */
//if(flag) 的flag默认是true //所以可以直接这样来判断 if(flag){ }
3、快捷键记录
ctrl + D ,快速复制此行到下一行
4、数学运算
//幂运算 Math.pow(a,b) //例如:2^3=8 Math.pow(2,3)
5、短路运算
int c = 5; boolean d = (c<4)&&(c++<4); System.out.println(d); System.out.println(c); //得到的结果:c是不变的,而d输出为false
6、位运算符
/* 位运算符是基于二进制 0 / 1 的 效率极高 & a&b 同为1,异为0 ^ a|b 有1则1 | a^b 同为0,异为1 ~ ~b 0转1,1转0 # 左移运算符 << 相当于 *2 >> 相当于 /2 */
7、Scanner IO流
对于Scanner的next和nextLine的区别
next遇到空白字符则结束读取字符,而nextLine则遇到回车符才会结束读取
public class scannerStr { //对于Scanner的next和nextLine的区别 //next遇到空白字符则结束读取字符,而nextLine则遇到回车符才会结束读取 public static void main(String[] args) { Scanner sc1 = new Scanner(System.in); Scanner sc2 = new Scanner(System.in); System.out.println("使用Scanner(IO流)的next方法键入数据并用str接收"); //键入数据则接收 if(sc1.hasNext()) { String str1 = sc1.next();//用str字符串去接收键盘所输入的内容 System.out.println(str1); } if(sc2.hasNextLine()) { String str2 = sc2.nextLine();//用str字符串去接收键盘所输入的内容 System.out.println(str2); } sc1.close(); sc2.close(); } }
8、判断Scanner键入的是整数还是小数
//要注意字符类型 public class scannerStr { //对于Scanner的next和nextLine的区别 //next遇到空白字符则结束读取字符,而nextLine则遇到回车符才会结束读取 public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = 0; float f = 0.0f; System.out.println("请输入整数:"); if(sc.hasNextInt()) { i = sc.nextInt(); System.out.println("整数"+i); } else { System.out.println("Not Int"); } System.out.println("请输入小数:"); if(sc.hasNextFloat()) { f = sc.nextFloat(); System.out.println("小数"+f); } else { System.out.println("Not Float"); } } }
9、输出Scanner所输入的数总和及其平均值
//在这犯了个错,忘了while循环的终止条件是非数字,所以一直在输入!!!需要输入非数字才结束输入 public class scannerStr { //对于Scanner的next和nextLine的区别 //next遇到空白字符则结束读取字符,而nextLine则遇到回车符才会结束读取 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = 0; double sum = 0.0; double ave = 0.0; //如果是数字那就一直在输入,所以需要输入非数字,如x等字符!!!若一直是数字则已知累加 while(scanner.hasNextDouble()) { double t = scanner.nextDouble(); m++; sum = sum + t; } ave = sum / m; System.out.println("共输入" + m + "个数字"); System.out.println("总和为:"+sum); System.out.println("平均为:"+ave); scanner.close(); } } //记录~~~~~~ equals方法 if(scanner.equals("hello")) System.out.println("输入为hello"); else System.out.println("输入错误“);